<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.css">
  <link rel="stylesheet" href="/lib/pace/pace-theme-minimal.min.css">
  <script src="/lib/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"lanqilu.github.io","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":true},"copycode":{"enable":true,"show_result":true,"style":null},"back2top":{"enable":true,"sidebar":true,"scrollpercent":true},"bookmark":{"enable":false,"color":"#395ca3","save":"auto"},"fancybox":true,"mediumzoom":false,"lazyload":false,"pangu":true,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="参考Xanxus-5&#x2F;NCRE-Python">
<meta property="og:type" content="article">
<meta property="og:title" content="二级Python基础">
<meta property="og:url" content="https://lanqilu.github.io/2019/09/03/Python/%E8%AE%A1%E7%AE%97%E6%9C%BA%E4%BA%8C%E7%BA%A7Python%E5%9F%BA%E7%A1%80/index.html">
<meta property="og:site_name" content="Halo">
<meta property="og:description" content="参考Xanxus-5&#x2F;NCRE-Python">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://puui.qpic.cn/fans_admin/0/3_1409075683_1572058823439/0">
<meta property="og:image" content="https://lanqilu.github.io/2019/09/03/Python/%E8%AE%A1%E7%AE%97%E6%9C%BA%E4%BA%8C%E7%BA%A7Python%E5%9F%BA%E7%A1%80/%E8%AE%A1%E7%AE%97%E6%9C%BA%E4%BA%8C%E7%BA%A7Python%E5%9F%BA%E7%A1%80/1568883436400.png">
<meta property="article:published_time" content="2019-09-03T05:17:39.000Z">
<meta property="article:modified_time" content="2020-07-06T07:16:29.248Z">
<meta property="article:author" content="Lanqilu">
<meta property="article:tag" content="Pyhton">
<meta property="article:tag" content="计算机二级">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://puui.qpic.cn/fans_admin/0/3_1409075683_1572058823439/0">

<link rel="canonical" href="https://lanqilu.github.io/2019/09/03/Python/%E8%AE%A1%E7%AE%97%E6%9C%BA%E4%BA%8C%E7%BA%A7Python%E5%9F%BA%E7%A1%80/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>二级Python基础 | Halo</title>
  
    <script async src="https://www.googletagmanager.com/gtag/js?id=UA-161500949-1"></script>
    <script data-pjax>
      if (CONFIG.hostname === location.hostname) {
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());
        gtag('config', 'UA-161500949-1');
      }
    </script>


  <script data-pjax>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?256151d1651e9d73ec980b2fc69de8f6";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">Halo</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签<span class="badge">39</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类<span class="badge">18</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档<span class="badge">85</span></a>

  </li>
        <li class="menu-item menu-item-python">

    <a href="/categories/Python/" rel="section"><i class="fa fa-fw fa-code"></i>Python</a>

  </li>
        <li class="menu-item menu-item-java">

    <a href="/categories/Java/" rel="section"><i class="fa fa-fw fa-code"></i>Java</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="reading-progress-bar"></div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://lanqilu.github.io/2019/09/03/Python/%E8%AE%A1%E7%AE%97%E6%9C%BA%E4%BA%8C%E7%BA%A7Python%E5%9F%BA%E7%A1%80/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="http://img.whl123456.top/image/avatar.jpg">
      <meta itemprop="name" content="Lanqilu">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Halo">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          二级Python基础
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2019-09-03 13:17:39" itemprop="dateCreated datePublished" datetime="2019-09-03T13:17:39+08:00">2019-09-03</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-07-06 15:16:29" itemprop="dateModified" datetime="2020-07-06T15:16:29+08:00">2020-07-06</time>
              </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <div class="note info no-icon">
            <p>参考<a href="https://github.com/Xanxus-5/NCRE-Python" target="_blank" rel="noopener">Xanxus-5/NCRE-Python</a></p>
          </div>

<a id="more"></a>
<p><img src="https://puui.qpic.cn/fans_admin/0/3_1409075683_1572058823439/0" alt=""></p>
<h2 id="程序设计基本方法"><a href="#程序设计基本方法" class="headerlink" title="程序设计基本方法"></a>程序设计基本方法</h2><h3 id="程序设计语言概述"><a href="#程序设计语言概述" class="headerlink" title="程序设计语言概述"></a>程序设计语言概述</h3><ul>
<li><p>程序设计语言是计算机能够理解和识别用户操作意图的一种交互体系，它按照特定规则组织计算机指令，使计算机能够自动进行各种运算处理。</p>
</li>
<li><p>按照程序设计语言规则组织起来的一组计算机指令称为计算机程序.</p>
</li>
<li><p>高级编程语言根据执行机制不同可分成两类：<strong>静态语言</strong>和<strong>脚本语言</strong>，静态语言采用编译方式执行，脚本语言采用解释方式执行。例如，C语言是静 态语言，Python语言是脚本语言。</p>
</li>
<li><p>采用<strong>编译执行的编程语言是静态语言</strong>，如C语言、Java语言；<strong>采用解释执行的编程语言是脚本语言</strong>，如JavaScript语言、PHP语言</p>
<ul>
<li><p><strong>编译</strong>是将源代码转换成目标代码的过程，通常，源代码是高级语言代码，目标代码是机器语言代码，执行编译的计算机程序称为编译器</p>
<blockquote>
<p>对于相同源代码，编译所产生的目标代码执行速度更快。</p>
<p>目标代码不需要编译器就可以运行，在同类型操作系统上使用灵活。</p>
</blockquote>
</li>
<li><p><strong>解释</strong>是将源代码逐条转换成目标代码同时逐条运行目标代码的过程。执行解释的计算机程序称为解释器。</p>
<blockquote>
<p>解释执行需要保留源代码，程序纠错和维护十分方便。</p>
<p>只要存在解释器，源代码可以在任何操作系统上运行，可移植性好</p>
</blockquote>
</li>
</ul>
</li>
</ul>
<h3 id="计算机编程"><a href="#计算机编程" class="headerlink" title="计算机编程"></a>计算机编程</h3><p>计算思维是区别于以数学为代表的逻辑思维和以物理为代表的实证思维的第三种思维模式。</p>
<p>编程是一个求解问题的过程</p>
<ul>
<li>首先需要分析问题，抽象内容之间的交互关系</li>
<li>设计利用计算机求解问题的确定性方法，</li>
<li>进而通过编写和调试代码解决问题</li>
</ul>
<p>这是从抽象问题到解决问题的完整过程。</p>
<h3 id="程序的基本编写方法"><a href="#程序的基本编写方法" class="headerlink" title="程序的基本编写方法"></a>程序的基本编写方法</h3><p>IPO程序编写方法</p>
<ul>
<li><p>输入数据</p>
<p>输入（Input）是一个程序的开始。程序要处理的数据有多种来源，形成了多种输入方式，包括：文件输入、网络输入、控制台输入、交互界面输出、随机数据输入、内部参数输入等。</p>
</li>
<li><p>处理数据</p>
<p>处理（Process）是程序对输入数据进行计算产生输出结果的过程。计算问题的处理方法统称为“算法”，它是程序最重要的组成部分。可以说，算法是一个程序的灵魂。</p>
</li>
<li><p>输出数据</p>
<p>输出（Output）是程序展示运算成果的方式。程序的输出方式包括：控制台输出、图形输出、文件输出、网络输出、操作系统内部变量输出等。</p>
</li>
</ul>
<h3 id="Python语言概述"><a href="#Python语言概述" class="headerlink" title="Python语言概述"></a>Python语言概述</h3><p>Python重要特点：</p>
<ol>
<li><p>具有通用性；</p>
<p>Python语言可以用于几乎任何与程序设计相关应用的开发，不仅适合训练变成思维，更适合诸如数据分析、机器学习、人工智能、Web开发等具体的技术领域。</p>
</li>
<li><p>语法简洁；</p>
<p>只有33个保留字</p>
</li>
<li><p>生态高产；</p>
<p>Python解释器提供了几百个内置类和函数库，此外，世界各地程序员通过开源社区贡献了十几万个第三方函数库，几乎覆盖了计算机技术的各个领域，编写Python程序可以大量利用已有内置或第三方代码，具备良好的编程生态。</p>
</li>
</ol>
<p>具体特点：</p>
<ol>
<li><p>平台无关；</p>
<p>Python程序可以在任何安装解释器的计算机环境中执行，因此，可以不经修改地实现跨操作系统运行。</p>
</li>
<li><p>强制可续；</p>
<p>Python通过强制缩进（类似文章段落的首行空格）来体现语句间的逻辑关系，显著提高了程序的可读性，进而增强了Python程序的可维护性。</p>
</li>
<li><p>支持中文；</p>
</li>
<li><p>格式多样；</p>
</li>
<li><p>类库便捷；</p>
</li>
<li><p>开源理念；</p>
</li>
</ol>
<h3 id="实例"><a href="#实例" class="headerlink" title="实例"></a>实例</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#斐波那契数列(F(n) = F(n-2) + F(n-1)）, n &gt;= 2)</span></span><br><span class="line">a, b = <span class="number">0</span>, <span class="number">1</span></span><br><span class="line"><span class="keyword">while</span> a &lt; <span class="number">1000</span> :</span><br><span class="line">    print(a, end = <span class="string">','</span>)</span><br><span class="line">a, b = b, a + b</span><br></pre></td></tr></table></figure>

<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#计算圆半径</span></span><br><span class="line">r = <span class="number">25</span></span><br><span class="line">area = <span class="number">3.1415</span> * r * r</span><br><span class="line">print(area)</span><br><span class="line">print(<span class="string">'&#123;:.2f&#125;'</span>.format(area)) <span class="comment">#两位小数</span></span><br></pre></td></tr></table></figure>

<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#绘制五角星</span></span><br><span class="line"><span class="keyword">from</span> turtle <span class="keyword">import</span> *</span><br><span class="line">color(<span class="string">'red'</span>, <span class="string">'red'</span>)</span><br><span class="line">begin_fill()</span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">5</span>):</span><br><span class="line">    fd(<span class="number">200</span>)</span><br><span class="line">    rt(<span class="number">144</span>)</span><br><span class="line">end_fill()</span><br><span class="line">done()</span><br></pre></td></tr></table></figure>

<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#程序运行计时</span></span><br><span class="line"><span class="keyword">import</span> time</span><br><span class="line">limit = <span class="number">10</span> * <span class="number">1000</span> * <span class="number">1000</span></span><br><span class="line">start = time.perf_counter()</span><br><span class="line"><span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">    limit -= <span class="number">1</span></span><br><span class="line">    <span class="keyword">if</span> limit &lt;= <span class="number">0</span>:</span><br><span class="line">        <span class="keyword">break</span></span><br><span class="line">delta = time.perf.counter() - start</span><br><span class="line">print(<span class="string">'时间是:&#123;&#125;秒'</span>.format(delta))</span><br></pre></td></tr></table></figure>

<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#绘制七种圆圈</span></span><br><span class="line"><span class="keyword">import</span> turtle</span><br><span class="line">colors = [<span class="string">'red'</span>, <span class="string">'orange'</span>, <span class="string">'yellow'</span>, <span class="string">'green'</span>, <span class="string">'blue'</span>, <span class="string">'indigo'</span>, <span class="string">'purple'</span>]</span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">7</span>):</span><br><span class="line">    c = color[i]</span><br><span class="line">    turtle.color(c.c)</span><br><span class="line">    turtle.begin_fill()</span><br><span class="line">    turtle.rt(<span class="number">360</span>/<span class="number">7</span>)</span><br><span class="line">    turtle.circle(<span class="number">50</span>)</span><br><span class="line">    turtle.end_fill()</span><br><span class="line">turtle.done()</span><br></pre></td></tr></table></figure>

<h2 id="Python基本语法元素"><a href="#Python基本语法元素" class="headerlink" title="Python基本语法元素"></a>Python基本语法元素</h2><h3 id="语法元素的名称"><a href="#语法元素的名称" class="headerlink" title="语法元素的名称"></a>语法元素的名称</h3><p><strong>缩进</strong>：表示程序的逻辑。指每行语句开始前的空白局域，用来表示Python程序之间的<strong>包含和层次关系</strong>。1个缩进 = 4个空格。缩进是Python语言中<strong>表明程序框架的唯一手段</strong>。</p>
<p><strong>注释</strong>：注释是代码中的辅助性文字，<strong>会被编译或解释器略去，不被计算机执行</strong>，一般用于程序员对代码的说明。Python语言采用#表示一行注释的开始，多行注释需要在每行开始都使用#。</p>
<p><strong>变量</strong>：可以随时命名、赋值、使用。</p>
<p><strong>命名</strong>：Python语言允许采用大写字母、小写字母、数字、下划线(_)和汉字等字符及其组合给变量命名，但名字的首字符不能是数字，中间不能出现空格，长度没有限制，标识符对大小写敏感。</p>
<p>保留字（keyword）：</p>
<table>
<thead>
<tr>
<th align="center">and</th>
<th align="center">as</th>
<th align="center">assert</th>
<th align="center">break</th>
<th align="center">class</th>
<th align="center">continue</th>
</tr>
</thead>
<tbody><tr>
<td align="center">def</td>
<td align="center">del</td>
<td align="center">elif</td>
<td align="center">else</td>
<td align="center">except</td>
<td align="center">False</td>
</tr>
<tr>
<td align="center">finally</td>
<td align="center">for</td>
<td align="center">from</td>
<td align="center">global</td>
<td align="center">if</td>
<td align="center">import</td>
</tr>
<tr>
<td align="center">in</td>
<td align="center">is</td>
<td align="center">lambda</td>
<td align="center">None</td>
<td align="center">nonlocal</td>
<td align="center">not</td>
</tr>
<tr>
<td align="center">or</td>
<td align="center">pass</td>
<td align="center">return</td>
<td align="center">True</td>
<td align="center">try</td>
<td align="center">while</td>
</tr>
<tr>
<td align="center">with</td>
<td align="center">yield</td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
</tr>
</tbody></table>
<h3 id="数据类型"><a href="#数据类型" class="headerlink" title="数据类型"></a>数据类型</h3><p>Python语言支持多种数据类型，最简单的包括数字类型、字符串类型，略微复杂的包括元组类型、集合类型、列表类型、字典类型等。</p>
<p><strong>数字类型</strong>：整数、浮点数、复数</p>
<p>一个整数值可以表示为十进制、十六进制、八进制和二进制等不同进制形式。</p>
<ul>
<li>二进制： 0b001111110010</li>
<li>八进制： 0o1762</li>
<li>十进制： 1010</li>
<li>十六进制：0x3F2</li>
</ul>
<p>一个浮点数可以表示为带有小数点的一般形式，也可以采用科学计数法表示。例如：浮点数123.456，两种表示方式如下：</p>
<ul>
<li>一般形式： 123.456</li>
<li>科学计数法： 1.23456e2</li>
</ul>
<p>复数类型与数学中的复数相一致，采用a+bj的形式表示，存在实部和虚部。</p>
<p><strong>字符串</strong>：双引号与单引号作用相同</p>
<p><strong>切片</strong>：[N : M]格式获取字符串的子串（从N到M但不包含M）。</p>
<p><img src="%E8%AE%A1%E7%AE%97%E6%9C%BA%E4%BA%8C%E7%BA%A7Python%E5%9F%BA%E7%A1%80/1568883436400.png" alt="1568883436400"></p>
<p><strong>如果字符串长度为L，正向递增需要以最左侧字符序号为0，向右依次递增，最右侧字符序号为L-1；</strong></p>
<p><strong>反向递减序号以最右侧字符序号为-1，向左依次递减，最左侧字符序号为-L。</strong></p>
<p>可以通过Python默认提供的<code>len()</code>函数获取字符串的长度，一个中文字符和西文字符的长度都记为1</p>
<h3 id="程序的语句元素"><a href="#程序的语句元素" class="headerlink" title="程序的语句元素"></a>程序的语句元素</h3><p><strong>表达式</strong>:产生或计算新数据值的代码片段称为表达式。</p>
<p><strong>赋值语句</strong>：&lt;变量&gt; = &lt;表达式&gt;</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 变量x和y交换</span></span><br><span class="line">t = x</span><br><span class="line">x = y</span><br><span class="line">y = t</span><br><span class="line"><span class="comment"># 等价于</span></span><br><span class="line">x, y = y, x</span><br></pre></td></tr></table></figure>

<p><strong>引用</strong>：</p>
<p>python程序会经常使用当前程序之外已有的功能代码，这个过程叫“引用”。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &lt;库名称&gt;</span><br><span class="line"><span class="comment"># 调用具体功能</span></span><br><span class="line">&lt;库名称&gt;.&lt;函数名称&gt;()</span><br></pre></td></tr></table></figure>

<h3 id="基本输入输出函数"><a href="#基本输入输出函数" class="headerlink" title="基本输入输出函数"></a>基本输入输出函数</h3><p><code>input()</code>:获得用户输入</p>
<p><code>&lt;变量&gt; = input(&quot;&lt;提示性文字&gt;&quot;)</code></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">a = input(<span class="string">'请输入：'</span>)</span><br><span class="line"><span class="comment"># &gt;请输入: X</span></span><br><span class="line">print(a)</span><br><span class="line"><span class="comment"># &gt;X</span></span><br></pre></td></tr></table></figure>

<p><code>eval()</code>：去掉字符串最外侧的引号。</p>
<p>以Python表达式的方式解析并执行字符串，将返回结果输出</p>
<p><code>&lt;变量&gt; = eval(&quot;&lt;字符串&gt;&quot;)</code></p>
<p><code>print()</code>：用于输出运算结果</p>
<ol>
<li><p>仅输出：<code>print(&#39;&lt;字符串&gt;&#39;)</code>；</p>
</li>
<li><p>仅输出一个或多个变量：<code>print(&lt;变量1&gt;, &lt;变量2&gt;, ..., &lt;变量n&gt;)</code>；</p>
</li>
<li><p>混合：<code>print(&lt;输出字符串模板&gt;.format(&lt;变量1&gt;, &lt;变量2&gt;..., &lt;变量n&gt;)</code>。例：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">a, b = <span class="number">3</span>, <span class="number">66</span></span><br><span class="line">print(<span class="string">'数字&#123;&#125;和数字&#123;&#125;的和是&#123;&#125;'</span>.format(a, b, a+b))</span><br><span class="line"><span class="comment"># &gt;数字3和数字66的和是69</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>默认会在最后增加一个换行，或用：<code>print(&#39;&lt;内容&gt;&#39;, end = &#39;&lt;结尾&gt;&#39;)</code></p>
</li>
</ol>
<h3 id="实例解析–倒背如流"><a href="#实例解析–倒背如流" class="headerlink" title="实例解析–倒背如流"></a>实例解析–倒背如流</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 将输入字符反向输出</span></span><br><span class="line"><span class="comment"># 方法一</span></span><br><span class="line"><span class="comment"># 采用正向递增序号，利用len()函数将i设为最后一个字符的索引序号，然后逐次输出至第一个字符。</span></span><br><span class="line">s = input(<span class="string">"请输入一段文本："</span>)</span><br><span class="line">i = len(s) - <span class="number">1</span></span><br><span class="line"><span class="keyword">while</span> i &gt;= <span class="number">0</span> :</span><br><span class="line">    print(s[i], end=<span class="string">""</span>)</span><br><span class="line">    i = i - <span class="number">1</span></span><br></pre></td></tr></table></figure>

<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 方法二</span></span><br><span class="line"><span class="comment"># 采用反向递减序号，将i首先设置为-1，直接索引最后一个字符，然后逐次输出至第一个字符。</span></span><br><span class="line">s = input(<span class="string">"请输入一段文本："</span>)</span><br><span class="line">i = <span class="number">-1</span></span><br><span class="line"><span class="keyword">while</span> i &gt;= <span class="number">-1</span> * len(s):</span><br><span class="line">    print(s[i], end=<span class="string">""</span>)</span><br><span class="line">    i = i - <span class="number">1</span></span><br></pre></td></tr></table></figure>

<h2 id="⭐基本数据类型"><a href="#⭐基本数据类型" class="headerlink" title="⭐基本数据类型"></a>⭐基本数据类型</h2><h3 id="⭐整数类型"><a href="#⭐整数类型" class="headerlink" title="⭐整数类型"></a>⭐整数类型</h3><table>
<thead>
<tr>
<th align="center">种类</th>
<th align="center">引导符号</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td align="center">十进制</td>
<td align="center">无</td>
<td>默认情况，例：1010,-1010</td>
</tr>
<tr>
<td align="center">二进制</td>
<td align="center">0b 或 0B</td>
<td>由字符0和1组成，例：0b1010，0B1010</td>
</tr>
<tr>
<td align="center">八进制</td>
<td align="center">0o 或 0O</td>
<td>由字符0到7组成，例：0o1010，0O1010</td>
</tr>
<tr>
<td align="center">十六进制</td>
<td align="center">0x 或 0X</td>
<td>由字符0到9、a 到 f 或 A 到 F 组成，例：0x1010，0X1010</td>
</tr>
</tbody></table>
<p>不同进制的整数可以<strong>直接运算</strong></p>
<h3 id="浮点数类型"><a href="#浮点数类型" class="headerlink" title="浮点数类型"></a>浮点数类型</h3><p>必须带有小数部分，小数可以是0。</p>
<p>除十进制外，浮点数没有其他进制表示形式</p>
<p>科学计算法使用字母 e 或 E 作为幂的符号，以10为基数</p>
<p>不确定尾数：两个浮点数运算，有一定概率在运算结果后增加一些不确定尾数</p>
<p><code>round()</code>函数：对字符串四舍五入。</p>
<p><code>round(1.2345, 2) = 1.23</code></p>
<h3 id="复数类型"><a href="#复数类型" class="headerlink" title="复数类型"></a>复数类型</h3><p>基本单位元素 j 或 J ,叫做“虚数单位”。含有虚数单位的数被称为复数</p>
<p>复数可以看作是二元有序实数对（a, b），表示 a + bj，a 是实数部分，b 是虚数部分。</p>
<p><strong>当 b 是1时，1不能省略，即’1j’表示复数</strong>而单独j则表示Python程序中的一个变量。</p>
<p>对于复数 z，可以用 <code>z.real</code> 和 <code>z.imag</code>分别获得它的实部和虚部</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">print((<span class="number">1.23e4</span> + <span class="number">5.67e4j</span>).real ) <span class="comment"># 12300.0</span></span><br><span class="line">print((<span class="number">1.23e4</span> + <span class="number">5.67e4j</span>).imag)  <span class="comment"># 56700.0</span></span><br><span class="line">print(<span class="number">1.23e4</span> + <span class="number">5.67e4j</span>.imag)    <span class="comment">#先获得5.67e4j的虚部，再与1.23e4进行求和计算 69000.0</span></span><br></pre></td></tr></table></figure>

<h3 id="数字类型的运算"><a href="#数字类型的运算" class="headerlink" title="数字类型的运算"></a>数字类型的运算</h3><h4 id="运算操作符"><a href="#运算操作符" class="headerlink" title="运算操作符"></a>运算操作符</h4><table>
<thead>
<tr>
<th align="center">操作符</th>
<th align="center">描述</th>
</tr>
</thead>
<tbody><tr>
<td align="center">x + y</td>
<td align="center">和</td>
</tr>
<tr>
<td align="center">x - y</td>
<td align="center">差</td>
</tr>
<tr>
<td align="center">x * y</td>
<td align="center">积</td>
</tr>
<tr>
<td align="center">x / y</td>
<td align="center">商，产生结果为浮点数</td>
</tr>
<tr>
<td align="center">x // y</td>
<td align="center">整数商，即：不大于 x 与 y 之商的最打整数</td>
</tr>
<tr>
<td align="center">x % y</td>
<td align="center">商的余数，称为模运算</td>
</tr>
<tr>
<td align="center">-x</td>
<td align="center">负值，即 x * (-1)</td>
</tr>
<tr>
<td align="center">+x</td>
<td align="center">x本身</td>
</tr>
<tr>
<td align="center">x ** y</td>
<td align="center">x 的 y 次幂</td>
</tr>
</tbody></table>
<p>基本规则：</p>
<ul>
<li><p>整数和浮点数混合运算，输出结果是浮点数；</p>
</li>
<li><p>整数之间运算，产生结果类型与操作符相关，<code>/</code> 的结果是浮点数；</p>
</li>
<li><p>整数或浮点数与复数运算，输出结果是复数；</p>
</li>
</ul>
<p><strong>所有</strong>二元运算操作符都可以与赋值符号（=）相连，形成<strong>增强赋值操作符</strong>（+=，-=等）。用 ‘op’ 表示运算操作符，增强赋值操作符的用法如下：</p>
<p>x op= y 等价于 x = x op y，op 与 = 之间不用加空格</p>
<h4 id="数值运算函数"><a href="#数值运算函数" class="headerlink" title="数值运算函数"></a>数值运算函数</h4><table>
<thead>
<tr>
<th align="center">函数</th>
<th align="center">描述</th>
</tr>
</thead>
<tbody><tr>
<td align="center"><code>abs(x)</code></td>
<td align="center">x的绝对值</td>
</tr>
<tr>
<td align="center"><code>divmod(x, y)</code></td>
<td align="center">(x // y, x % y)，输出为二元组形式（也称为元组类型）</td>
</tr>
<tr>
<td align="center"><code>pow(x, y[, z])</code></td>
<td align="center">x*<em>y[(x *</em>y) % z]，幂运算</td>
</tr>
<tr>
<td align="center"><code>round(x[, d])</code></td>
<td align="center">对 x 四舍五入，保留 d 位小数</td>
</tr>
<tr>
<td align="center"><code>max(a, b, c, d, ...)</code></td>
<td align="center">最大值</td>
</tr>
<tr>
<td align="center"><code>min(a, b, c, d, ...)</code></td>
<td align="center">最小值</td>
</tr>
</tbody></table>
<h3 id="字符串类型及格式化"><a href="#字符串类型及格式化" class="headerlink" title="字符串类型及格式化"></a>字符串类型及格式化</h3><p>单行字符串可以由一对单引号或双引号作为边界表示<br>多行字符串可以由一对三单引号或三双引号作为边界表示</p>
<p>反斜杠字符（<code>\</code>）表示“转义”，即该字符与后面相邻的一个字符共同组成了新的含义。</p>
<ul>
<li><code>\n</code>：换行；</li>
<li><code>\\</code>：反斜杠</li>
<li><code>\&#39;</code>表示单引号</li>
<li><code>\&quot;</code>表示双引号</li>
<li><code>\t</code>：制表符</li>
</ul>
<p><strong><code>\</code> 的额外作用：续行</strong></p>
<h4 id="format-方法的基本使用"><a href="#format-方法的基本使用" class="headerlink" title="format()方法的基本使用"></a><code>format()</code>方法的基本使用</h4><p>字符串<code>format()</code>方法的基本使用格式是：<code>&lt;模板字符串&gt;.format(&lt;逗号分隔的参数&gt;)</code></p>
<p>模板字符串是一个由字符串和槽组成的字符，用来控制字符串和变量的显示效果</p>
<p><code>{&lt;参数符号&gt;:&lt;格式控制标记&gt;}</code></p>
<p><code>:</code>引导符号</p>
<p>格式控制标记包括：<code>&lt;填充&gt;</code>、<code>&lt;对齐&gt;</code>、<code>&lt;宽度&gt;</code>、<code>&lt;.(精度)&gt;</code>、<code>英文逗号</code>、<code>&lt;类型&gt;</code>6个字段，这些字段都是可选的，可以组合使用</p>
<p><code>&lt;填充&gt;</code>、<code>&lt;对齐&gt;</code>和<code>&lt;宽度&gt;</code>主要用于对显示格式的规范。</p>
<ul>
<li><p><code>&lt;填充&gt;</code>:可以修改默认填充字符，填充字符只能有一个。</p>
</li>
<li><p><code>&lt;对齐&gt;</code>:<code>&lt;</code> 左对齐；<code>&gt;</code>右对齐；<code>^</code> 居中</p>
</li>
<li><p><code>&lt;宽度&gt;</code>:槽的设定输出宽度<br>宽度指当前槽的设定输出字符宽度，如果该槽参数实际值比宽度设定值大，则使用参数实际长度。如果该值的实际位数小于指定宽度，则按照对齐指定方式在宽度内对齐，默认以空格字符补充。</p>
</li>
<li><p><code>英文逗号</code>:数字的千位分隔符，适用于整数和浮点数<br><code>&lt;.精度&gt;</code> <code>&lt;类型&gt;</code>主要用于对数值本身的规范</p>
</li>
<li><p><code>&lt;.(精度)&gt;</code>:浮点数小数部分的精度或字符串的最大输出长度</p>
</li>
<li><p><code>&lt;类型&gt;</code>:整数类型：b, c, d, o, x, X；浮点数类型：e, E, f, %</p>
</li>
</ul>
<p>整数类型：</p>
<ul>
<li>b：输出整数的二进制方式；</li>
<li>c：输出整数对应的Unicode字符；</li>
<li>d：输出整数的十进制方式；</li>
<li>o：输出整数的八进制方式；</li>
<li>x：输出整数的小写十六进制方式；</li>
<li>X：输出整数的大写十六进制方式</li>
</ul>
<p>浮点类型：</p>
<ul>
<li>e：输出浮点数对应的小写字母e的指数形式；</li>
<li>E：输出浮点数对应的大写字母E的指数形式</li>
<li>f：输出浮点数的标准浮点形式；</li>
<li>%：输出浮点数的百分形式</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">print(<span class="string">'&#123;:.2f&#125;'</span>.format(<span class="number">3.14159</span>)) <span class="comment">#输出小数后2位</span></span><br><span class="line"><span class="comment"># '3.14'</span></span><br><span class="line">print(<span class="string">'&#123;:X&#125;'</span>.format(<span class="number">1010</span>)) <span class="comment">#输出十六进制形式</span></span><br><span class="line"><span class="comment"># '3F2'</span></span><br><span class="line">print(<span class="string">'&#123;:.5&#125;'</span>.format(<span class="string">'这是一个很长的字符串'</span>)) <span class="comment">#输出前5位</span></span><br><span class="line"><span class="comment"># '这是一个很'</span></span><br><span class="line">print(<span class="string">'&#123;:-^10&#125;'</span>.format(<span class="string">'PYTHON'</span>)) <span class="comment">#居中并以 - 填充</span></span><br><span class="line"><span class="comment"># '--PYTHON--'</span></span><br></pre></td></tr></table></figure>

<h3 id="字符串类型的操作"><a href="#字符串类型的操作" class="headerlink" title="字符串类型的操作"></a>字符串类型的操作</h3><h4 id="字符串操作符"><a href="#字符串操作符" class="headerlink" title="字符串操作符"></a>字符串操作符</h4><table>
<thead>
<tr>
<th align="center">操作符</th>
<th align="center">描述</th>
</tr>
</thead>
<tbody><tr>
<td align="center">x + y</td>
<td align="center">连接两个字符串 x 与 y</td>
</tr>
<tr>
<td align="center">x *n 或 n* x</td>
<td align="center">复制 n 次字符串 x</td>
</tr>
<tr>
<td align="center">x in s</td>
<td align="center">如果 x 是 s 的字符串，返回True，否则False</td>
</tr>
</tbody></table>
<h4 id="字符串处理函数"><a href="#字符串处理函数" class="headerlink" title="字符串处理函数"></a>字符串处理函数</h4><table>
<thead>
<tr>
<th align="center">函数</th>
<th align="center">描述</th>
</tr>
</thead>
<tbody><tr>
<td align="center"><code>len(x)</code></td>
<td align="center">返回 x 的长度，也可以返回其他组合数据类型的元素个数</td>
</tr>
<tr>
<td align="center"><code>str(x)</code></td>
<td align="center">返回任意类型 x 的字符串形式</td>
</tr>
<tr>
<td align="center"><code>chr(x)</code></td>
<td align="center">返回 Unicode 编码 x 对应的单字符</td>
</tr>
<tr>
<td align="center"><code>ord(x)</code></td>
<td align="center">返回单字符 x 表示的 Unicod 编码</td>
</tr>
<tr>
<td align="center"><code>hex(x)</code></td>
<td align="center">返回整数 x 对应十六进制的小写形式字符串</td>
</tr>
<tr>
<td align="center"><code>oct(x)</code></td>
<td align="center">返回整数 x 对应八进制的小写形式字符串</td>
</tr>
</tbody></table>
<h4 id="字符串处理方法"><a href="#字符串处理方法" class="headerlink" title="字符串处理方法"></a>字符串处理方法</h4><table>
<thead>
<tr>
<th align="center">方法</th>
<th align="center">描述</th>
</tr>
</thead>
<tbody><tr>
<td align="center"><code>str.lower(x)</code></td>
<td align="center">返回 str 全部小写</td>
</tr>
<tr>
<td align="center"><code>str.upper(x)</code></td>
<td align="center">返回 str 全部大写</td>
</tr>
<tr>
<td align="center"><code>str.split(sep = None)</code></td>
<td align="center">返回由 str 根据 sep 被分割构成的列表，默认以空格分割</td>
</tr>
<tr>
<td align="center"><code>str.count(sub)</code></td>
<td align="center">返回 sub 出现的次数</td>
</tr>
<tr>
<td align="center"><code>str.replace(old, new)</code></td>
<td align="center">返回 old 被替换为 new 的 str</td>
</tr>
<tr>
<td align="center"><code>str.center(width, fillchar)</code></td>
<td align="center">字符串居中函数，fillchar 可选，两侧新增字符采用fillchar填充</td>
</tr>
<tr>
<td align="center"><code>str.strip(chars)</code></td>
<td align="center">从 str 中去掉其左右 chars 中列出的字符</td>
</tr>
<tr>
<td align="center"><code>str.join(iter)</code></td>
<td align="center">将 iter 变量的每一个元素后增加一个 str</td>
</tr>
</tbody></table>
<p>例：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">print(<span class="string">'Python is an excellent language.'</span>.replace(<span class="string">'a'</span>, <span class="string">'#'</span>))</span><br><span class="line"><span class="comment"># 'Python is #n excellent l#ngu#ge.'</span></span><br><span class="line">print(<span class="string">'Python'</span>.center(<span class="number">20</span>, <span class="string">'='</span>))</span><br><span class="line"><span class="comment"># '===Python==='</span></span><br><span class="line">print(<span class="string">'Python'</span>.center(<span class="number">2</span>, <span class="string">'='</span>))</span><br><span class="line"><span class="comment"># 'Python' #当 width 小于 str 长度，返回 str</span></span><br><span class="line">print(<span class="string">'   ==Python==   '</span>.strip(<span class="string">' =n'</span>))</span><br><span class="line"><span class="comment"># 'Pytho'</span></span><br><span class="line">print(<span class="string">','</span>.join(<span class="string">'12345'</span>))</span><br><span class="line"><span class="comment"># '1,2,3,4,5'</span></span><br></pre></td></tr></table></figure>

<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">main</span><span class="params">()</span>:</span></span><br><span class="line">    str1 = <span class="string">'hello, world!'</span></span><br><span class="line">    str2 = <span class="string">'HeLLo, wOrld!'</span></span><br><span class="line">    <span class="comment"># 通过len函数计算字符串的长度</span></span><br><span class="line">    print(len(str1))  <span class="comment"># 13</span></span><br><span class="line">    <span class="comment"># 获得字符串首字母大写的copy</span></span><br><span class="line">    print(str1.capitalize())  <span class="comment"># Hello, world!</span></span><br><span class="line">    <span class="comment"># 获得字符串变大写后的copy</span></span><br><span class="line">    print(str1.title())  <span class="comment"># Hello, World!</span></span><br><span class="line">    print(str2.title())  <span class="comment"># Hello, World!</span></span><br><span class="line">    <span class="comment"># 获得以首字母大写的方式显示每个单词后的copy</span></span><br><span class="line">    print(str1.upper())  <span class="comment"># HELLO, WORLD!</span></span><br><span class="line">    print(str2.lower())  <span class="comment"># hello, world!</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</span><br><span class="line">    main()</span><br></pre></td></tr></table></figure>

<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">main</span><span class="params">()</span>:</span></span><br><span class="line">    str1 = <span class="string">'hello, world!'</span></span><br><span class="line">    <span class="comment"># 从字符串中查找子串所在位置</span></span><br><span class="line">    print(str1.find(<span class="string">'or'</span>))  <span class="comment"># 8</span></span><br><span class="line">    print(str1.find(<span class="string">'shit'</span>))  <span class="comment"># -1</span></span><br><span class="line">    <span class="comment"># 与find类似但找不到子串时会引发异常</span></span><br><span class="line">    print(str1.index(<span class="string">'or'</span>)) <span class="comment"># 8</span></span><br><span class="line">    print(str1.index(<span class="string">'shit'</span>)) <span class="comment"># ValueError: substring not found</span></span><br><span class="line">    <span class="comment"># 检查字符串是否以指定的字符串开头</span></span><br><span class="line">    print(str1.startswith(<span class="string">'He'</span>))  <span class="comment"># False</span></span><br><span class="line">    print(str1.startswith(<span class="string">'hel'</span>))  <span class="comment"># True</span></span><br><span class="line">    <span class="comment"># 检查字符串是否以指定的字符串结尾</span></span><br><span class="line">    print(str1.endswith(<span class="string">'!'</span>))  <span class="comment"># True</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</span><br><span class="line">    main()</span><br></pre></td></tr></table></figure>

<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">main</span><span class="params">()</span>:</span></span><br><span class="line">    str1 = <span class="string">'hello, world!'</span></span><br><span class="line">    <span class="comment"># 将字符串以指定的宽度居中并在两侧填充指定的字符</span></span><br><span class="line">    print(str1.center(<span class="number">50</span>, <span class="string">'*'</span>))</span><br><span class="line">    <span class="comment"># 将字符串以指定的宽度靠右放置左侧填充指定的字符</span></span><br><span class="line">    print(str1.rjust(<span class="number">50</span>, <span class="string">' '</span>))</span><br><span class="line">    str3 = <span class="string">'abc123456'</span></span><br><span class="line">    <span class="comment"># 从字符串中取出指定位置的字符(下标运算)</span></span><br><span class="line">    print(str3[<span class="number">2</span>])  <span class="comment"># c</span></span><br><span class="line">    <span class="comment"># 字符串切片(从指定的开始索引到指定的结束索引)</span></span><br><span class="line">    print(str3[<span class="number">2</span>:<span class="number">5</span>])  <span class="comment"># c12</span></span><br><span class="line">    print(str3[<span class="number">2</span>:])  <span class="comment"># c123456</span></span><br><span class="line">    print(str3[<span class="number">2</span>::<span class="number">2</span>])  <span class="comment"># c246</span></span><br><span class="line">    print(str3[::<span class="number">2</span>])  <span class="comment"># ac246</span></span><br><span class="line">    print(str3[::<span class="number">-1</span>])  <span class="comment"># 654321cba</span></span><br><span class="line">    print(str3[<span class="number">-3</span>:<span class="number">-1</span>])  <span class="comment"># 45</span></span><br><span class="line">    <span class="comment"># 检查字符串是否由数字构成</span></span><br><span class="line">    print(str3.isdigit())  <span class="comment"># False</span></span><br><span class="line">    <span class="comment"># 检查字符串是否以字母构成</span></span><br><span class="line">    print(str3.isalpha())  <span class="comment"># False</span></span><br><span class="line">    <span class="comment"># 检查字符串是否以数字和字母构成</span></span><br><span class="line">    print(str3.isalnum())  <span class="comment"># True</span></span><br><span class="line">    str4 = <span class="string">'  hello, worl d   '</span></span><br><span class="line">    print(str4)</span><br><span class="line">    <span class="comment"># 获得字符串修剪空格的拷贝</span></span><br><span class="line">    print(str4.strip())  <span class="comment"># 'hello, worl d'</span></span><br><span class="line">    print(str4.rstrip()) <span class="comment"># '  hello, worl d   '</span></span><br><span class="line">    print(str4.lstrip()) <span class="comment"># 'hello, worl d   '</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</span><br><span class="line">    main()</span><br></pre></td></tr></table></figure>

<h4 id="类型判断和类型间转换"><a href="#类型判断和类型间转换" class="headerlink" title="类型判断和类型间转换"></a>类型判断和类型间转换</h4><p><code>type(x)</code>：对 x 进行类型判断，适用于任何数据类型</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">n = eval(input(<span class="string">'请输入一个数字：'</span>))</span><br><span class="line"><span class="keyword">if</span> type(n) == type(<span class="number">123</span>):</span><br><span class="line">    print(<span class="string">'输入的是整数'</span>)</span><br><span class="line"><span class="keyword">elif</span> type(n) == type(<span class="number">11.3</span>):</span><br><span class="line">    print(<span class="string">'输入的是浮点数'</span>)</span><br><span class="line"><span class="keyword">else</span> :</span><br><span class="line">    print(<span class="string">'无法判断'</span>)</span><br></pre></td></tr></table></figure>

<p><code>int(x)</code>：将 x 转为整数</p>
<p><code>float(x)</code>：将 x 转为浮点数</p>
<p><code>str(x)</code>：将 x 转为字符串</p>
<h3 id="实例解析–凯撒密码"><a href="#实例解析–凯撒密码" class="headerlink" title="实例解析–凯撒密码"></a>实例解析–凯撒密码</h3><p>恺撒撒密码是古罗马恺撒大帝用来对军事情报进行加密的算法，它采用了替换方法对信息中的每一个英文字符循环替换为字母表序列该字符后面第三个字符：<br>原文：A B C D E F G H I J K L M N O P Q R S T U V W X Y Z<br>密文：D E F G H I J K L M N O P Q R S T U V W X Y Z A B C</p>
<p>原文字符P，其密文字符C满足如下条件：C = ( P + 3 ) mod 26</p>
<p>解密方法反之，满足：P = ( C – 3 ) mod 26</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 恺撒密码-加密</span></span><br><span class="line">ptxt = input(<span class="string">"请输入明文文本: "</span>)</span><br><span class="line"><span class="keyword">for</span> p <span class="keyword">in</span> ptxt:</span><br><span class="line">    <span class="keyword">if</span> <span class="string">"a"</span> &lt;= p &lt;= <span class="string">"z"</span>:</span><br><span class="line">        print(chr(ord(<span class="string">"a"</span>)+(ord(p)-ord(<span class="string">"a"</span>)+<span class="number">3</span>)%<span class="number">26</span>), end=<span class="string">''</span>)</span><br><span class="line">    <span class="keyword">elif</span> <span class="string">"A"</span> &lt;= p &lt;= <span class="string">"Z"</span>:</span><br><span class="line">            print(chr(ord(<span class="string">"A"</span>)+(ord(p)-ord(<span class="string">"A"</span>)+<span class="number">3</span>)%<span class="number">26</span>), end=<span class="string">''</span>)</span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">            print(p, end=<span class="string">''</span>)</span><br></pre></td></tr></table></figure>

<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 恺撒密码-解密</span></span><br><span class="line">etxt = input(<span class="string">"请输入加密后文本: "</span>)</span><br><span class="line"><span class="keyword">for</span> p <span class="keyword">in</span> etxt:</span><br><span class="line">    <span class="keyword">if</span> <span class="string">"a"</span> &lt;= p &lt;= <span class="string">"z"</span>:</span><br><span class="line">        print(chr(ord(<span class="string">"a"</span>)+(ord(p)-ord(<span class="string">"a"</span>)<span class="number">-3</span>)%<span class="number">26</span>), end=<span class="string">''</span>)</span><br><span class="line">    <span class="keyword">elif</span> <span class="string">"A"</span> &lt;= p &lt;= <span class="string">"Z"</span>:</span><br><span class="line">            print(chr(ord(<span class="string">"A"</span>)+(ord(p)-ord(<span class="string">"A"</span>)<span class="number">-3</span>)%<span class="number">26</span>), end=<span class="string">''</span>)</span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">            print(p, end=<span class="string">''</span>)</span><br></pre></td></tr></table></figure>

<h2 id="程序的控制结构"><a href="#程序的控制结构" class="headerlink" title="程序的控制结构"></a>程序的控制结构</h2><h3 id="程序流程图"><a href="#程序流程图" class="headerlink" title="程序流程图"></a>程序流程图</h3><p>描述一个计算问题的程序过程有多种方式：IPO、流程图、伪代码和程序代码。</p>
<ul>
<li>起止框：表示程序逻辑的开始或结束；</li>
<li>判断框：表示一个判断条件，并根据判断结果选择不同的执行路径；</li>
<li>处理框：表示一组处理过程，对应于顺序执行的程序逻辑；</li>
<li>输入输出框：表示程序中的数据输入或结果输出；</li>
<li>注释框：表示程序的注释；</li>
<li>流向线：表示程序的控制流，以带箭头直线或曲线表达程序的执行路径；</li>
<li>连接点：表示多个流程图的连接方式，常用于将多个较小流程图组织成较大流程图。</li>
</ul>
<h3 id="程序控制结构"><a href="#程序控制结构" class="headerlink" title="程序控制结构"></a>程序控制结构</h3><p>三种基本结构：</p>
<ol>
<li>顺序结构：按照线性顺序依次执行；</li>
<li>分支结构：根据条件判断结果而选择不同向前执行路径；</li>
<li>循环结构：根据条件判断结果向后执行的一种运行方式。</li>
</ol>
<p>任何程序都由这三种基本结构组合而成</p>
<h3 id="单分支结构-if语句"><a href="#单分支结构-if语句" class="headerlink" title="单分支结构: if语句"></a>单分支结构: if语句</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> &lt;条件&gt; :</span><br><span class="line">    &lt;语句块&gt;</span><br></pre></td></tr></table></figure>

<p>&lt;条件&gt;可一个或多个，用 and 与 or 连接多个条件。</p>
<h4 id="二分支结构-if-else语句"><a href="#二分支结构-if-else语句" class="headerlink" title="二分支结构: if-else语句"></a>二分支结构: if-else语句</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> &lt;条件&gt; :</span><br><span class="line">    &lt;语句块<span class="number">1</span>&gt;</span><br><span class="line"><span class="keyword">else</span> :</span><br><span class="line">    &lt;语句块<span class="number">2</span>&gt;</span><br></pre></td></tr></table></figure>

<p>更简洁的表达方式：适合&lt;语句块1&gt;和&lt;语句块2&gt;都只包含简单表达式的情况。</p>
<p><code>&lt;表达式1&gt; if &lt;条件&gt; else &lt;表达式2&gt;</code></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">s = eval(input(<span class="string">'请输入一个整数：'</span>))</span><br><span class="line">token = <span class="string">''</span> <span class="keyword">if</span> s % <span class="number">3</span> == <span class="number">0</span> <span class="keyword">and</span> s % <span class="number">5</span> == <span class="number">0</span> <span class="keyword">else</span> <span class="string">"不"</span></span><br><span class="line">print(<span class="string">'这个数字&#123;&#125;能够同时被3和5整除。'</span>.format(token))</span><br></pre></td></tr></table></figure>

<h4 id="多分支结构-if-elif-else语句"><a href="#多分支结构-if-elif-else语句" class="headerlink" title="多分支结构: if-elif-else语句"></a>多分支结构: if-elif-else语句</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> &lt;条件<span class="number">1</span>&gt; :</span><br><span class="line">    &lt;语句<span class="number">1</span>&gt;</span><br><span class="line"><span class="keyword">elif</span> &lt;条件<span class="number">2</span>&gt; :</span><br><span class="line">    &lt;语句<span class="number">2</span>&gt;</span><br><span class="line">    ...</span><br><span class="line"><span class="keyword">else</span> :</span><br><span class="line">    &lt;语句N&gt;</span><br></pre></td></tr></table></figure>

<p>按照多分支结构的代码顺序依次评估判断条件，寻找并执行第一个结果为 True 条件对应的语句块，然后跳过整个 if - elif -else 结构。（只有条件为 False 才会进入 elif）</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">score = eval(input(<span class="string">'输入成绩：'</span>))</span><br><span class="line"><span class="keyword">if</span> score &gt;= <span class="number">90</span> :</span><br><span class="line">    grade = <span class="string">'A'</span></span><br><span class="line"><span class="keyword">elif</span> score &gt;= <span class="number">80</span> :</span><br><span class="line">    grade = <span class="string">'B'</span></span><br><span class="line"><span class="keyword">elif</span> score &gt;= <span class="number">70</span> :</span><br><span class="line">    grade = <span class="string">'C'</span></span><br><span class="line"><span class="keyword">elif</span> score &gt;= <span class="number">60</span> :</span><br><span class="line">    grade = <span class="string">'D'</span></span><br><span class="line"><span class="keyword">else</span> :</span><br><span class="line">    grade = <span class="string">'E'</span></span><br><span class="line">print(<span class="string">'对应的等级是：&#123;&#125;'</span>.format(grade))</span><br></pre></td></tr></table></figure>

<h3 id="判断条件及组合"><a href="#判断条件及组合" class="headerlink" title="判断条件及组合"></a>判断条件及组合</h3><p>判断条件可以使用任何能够产生 True 或 False 的语句或函数</p>
<table>
<thead>
<tr>
<th align="center">操作符</th>
<th align="center">数学符号</th>
<th align="center">含义</th>
</tr>
</thead>
<tbody><tr>
<td align="center">&lt;</td>
<td align="center">&lt;</td>
<td align="center">小于</td>
</tr>
<tr>
<td align="center">&lt;=</td>
<td align="center">$\leq$</td>
<td align="center">小于等于</td>
</tr>
<tr>
<td align="center">&gt;=</td>
<td align="center">$\geq$</td>
<td align="center">大于等于</td>
</tr>
<tr>
<td align="center">&gt;</td>
<td align="center">&gt;</td>
<td align="center">大于</td>
</tr>
<tr>
<td align="center">==</td>
<td align="center">=</td>
<td align="center">等于</td>
</tr>
<tr>
<td align="center">!=</td>
<td align="center">$\neq$</td>
<td align="center">不等于</td>
</tr>
</tbody></table>
<p>Python 中，任何非零的数值、非空的数据类型都等价于 True，反之可以可直接用作判断条件。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">print(<span class="number">0</span> == <span class="literal">False</span>)</span><br><span class="line"><span class="comment"># True</span></span><br><span class="line">print(<span class="string">''</span> == <span class="literal">True</span>)</span><br><span class="line"><span class="comment"># False</span></span><br></pre></td></tr></table></figure>

<p>Python语言使用保留字not、and和or对条件进行逻辑运算或组合</p>
<p>not : 否；and : 与；or : 或</p>
<h3 id="程序的循环结构"><a href="#程序的循环结构" class="headerlink" title="程序的循环结构"></a>程序的循环结构</h3><p>Python语言的循环结构包括两种：遍历循环和无限循环。</p>
<ul>
<li>遍历循环使用保留字<code>for</code>依次提取遍历结构各元素进行处理；</li>
<li>无限循环使用保留字<code>while</code>根据判断条件执行程序。</li>
</ul>
<h4 id="遍历循环-for"><a href="#遍历循环-for" class="headerlink" title="遍历循环: for"></a>遍历循环: for</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> &lt;循环变量&gt; <span class="keyword">in</span> &lt;遍历结构&gt; :</span><br><span class="line">    &lt;语句&gt;</span><br></pre></td></tr></table></figure>

<p>遍历结构可以是字符串、文件、<code>range()</code>函数或组合数据类型等。</p>
<p>字符串：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> &lt;循环变量&gt; <span class="keyword">in</span> &lt;字符串&gt; :</span><br><span class="line">    &lt;语句块&gt;</span><br></pre></td></tr></table></figure>

<p><code>range()</code>函数：可以制定语句块的循环次数。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> &lt;循环变量&gt; <span class="keyword">in</span> range(&lt;循环次数&gt;) :</span><br><span class="line">    &lt;语句块&gt;</span><br></pre></td></tr></table></figure>

<p>扩展模式：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> &lt;变量&gt; <span class="keyword">in</span> &lt;结构&gt; :</span><br><span class="line">    &lt;语句<span class="number">1</span>&gt;</span><br><span class="line"><span class="keyword">else</span> :</span><br><span class="line">    &lt;语句<span class="number">2</span>&gt;</span><br></pre></td></tr></table></figure>

<p>当 for 循环正常结束后，程序会执行 else 语句。</p>
<p>else语句只在循环正常执行之后才执行并结束，因此，可以在&lt;语句块2&gt;中放置判断循环执行情况的语句。</p>
<h4 id="无限循环-while"><a href="#无限循环-while" class="headerlink" title="无限循环: while"></a>无限循环: while</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">while</span> &lt;条件&gt; :</span><br><span class="line">    &lt;语句块&gt;</span><br></pre></td></tr></table></figure>

<p>&lt;条件&gt;与 if 一样，结果为 True 或 False。</p>
<p>当判断条件为 True，执行循环体语句，结束后再次判断条件；当 False，循环终止，执行与 while 同级别缩进的后续语句。</p>
<p>else 扩展：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">while</span> &lt;条件&gt; :</span><br><span class="line">    &lt;语句<span class="number">1</span>&gt;</span><br><span class="line"><span class="keyword">else</span> :</span><br><span class="line">    &lt;语句<span class="number">2</span>&gt;</span><br></pre></td></tr></table></figure>

<h4 id="循环控制-break和continue"><a href="#循环控制-break和continue" class="headerlink" title="循环控制: break和continue"></a>循环控制: break和continue</h4><p><code>break</code> : 用来跳出<strong>最内层</strong> for 或 while 循环，脱离后从循环后的代码继续执行。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">while</span> <span class="literal">True</span> :</span><br><span class="line">    s = input(<span class="string">'请输入名字(按Q退出)：'</span>)</span><br><span class="line">    <span class="keyword">if</span> s == <span class="string">'Q'</span> :</span><br><span class="line">        <span class="keyword">break</span></span><br><span class="line">    print(<span class="string">'输入的是：'</span>, s)</span><br><span class="line">print(<span class="string">'程序退出'</span>)</span><br></pre></td></tr></table></figure>

<p><code>continue</code> : 结束当前当次循环，跳出循环体下面尚未执行的语句，但不跳出整个循环。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> s <span class="keyword">in</span> <span class="string">'PYTHON'</span> :</span><br><span class="line">    <span class="keyword">if</span> s == <span class="string">'Y'</span> :</span><br><span class="line">        <span class="keyword">continue</span></span><br><span class="line">    print(s, end = <span class="string">''</span>)</span><br></pre></td></tr></table></figure>

<p><code>continue</code>语句和<code>break</code>语句的区别是：<code>continue</code>语句只结束本次循环，不终止整个循环的执行，而<code>break</code>具备结束循环的能力。</p>
<h3 id="程序的异常处理"><a href="#程序的异常处理" class="headerlink" title="程序的异常处理"></a>程序的异常处理</h3><h4 id="try-except"><a href="#try-except" class="headerlink" title="try  except"></a>try  except</h4><p>Python 用 try 和 except 进行异常处理。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">try</span> :</span><br><span class="line">    &lt;语句<span class="number">1</span>&gt;</span><br><span class="line"><span class="keyword">except</span> :</span><br><span class="line">    &lt;语句<span class="number">2</span>&gt;</span><br></pre></td></tr></table></figure>

<p>语句1是正常执行的程序内容，当执行这个语句发生异常时，则执行 except 后的语句2。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">try</span> :</span><br><span class="line">    n = eval(input(<span class="string">'请输入一个数字：'</span>))</span><br><span class="line">    print(<span class="string">'输入数字的3次方的值为：'</span>, n ** <span class="number">3</span>)</span><br><span class="line"><span class="keyword">except</span> :</span><br><span class="line">    print(<span class="string">'输入错误，请输入一个数字！'</span>)</span><br></pre></td></tr></table></figure>

<h3 id="实例解析——猜数字游戏"><a href="#实例解析——猜数字游戏" class="headerlink" title="实例解析——猜数字游戏"></a>实例解析——猜数字游戏</h3><p>编写一个“猜数字游戏”的程序，在1到1000之间随机产生一个数，然后请用户循环猜测这个数字，对于每个答案只回答“猜大了”或“猜小了”，直到猜测准确为止，输出用户的猜测次数。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> random</span><br><span class="line">target = random.randint(<span class="number">1</span>, <span class="number">1000</span>)</span><br><span class="line">count = <span class="number">0</span></span><br><span class="line"><span class="keyword">while</span> <span class="literal">True</span> :</span><br><span class="line">    <span class="keyword">try</span> :</span><br><span class="line">        guess = eval(input(<span class="string">'请输入一个猜测的整数（1至1000）：'</span>))</span><br><span class="line">    <span class="keyword">except</span> :</span><br><span class="line">        print(<span class="string">'输入有误，请重试。'</span>)</span><br><span class="line">        <span class="keyword">continue</span></span><br><span class="line">    count = count + <span class="number">1</span></span><br><span class="line">    <span class="keyword">if</span> guess &gt; target :</span><br><span class="line">        print(<span class="string">'大了'</span>)</span><br><span class="line">    <span class="keyword">elif</span> guess &lt; target :</span><br><span class="line">        print(<span class="string">'小了'</span>)</span><br><span class="line">    <span class="keyword">else</span> :</span><br><span class="line">        print(<span class="string">'猜对了'</span>)</span><br><span class="line">        <span class="keyword">break</span></span><br><span class="line">print(<span class="string">'此轮的猜测次数是：'</span>, count)</span><br></pre></td></tr></table></figure>

<h2 id="函数和代码复用"><a href="#函数和代码复用" class="headerlink" title="函数和代码复用"></a>函数和代码复用</h2><h3 id="函数的定义：def"><a href="#函数的定义：def" class="headerlink" title="函数的定义：def"></a>函数的定义：def</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> &lt;函数名&gt;<span class="params">(&lt;参数列表&gt;)</span> :</span></span><br><span class="line">    &lt;函数体&gt;</span><br><span class="line">    <span class="keyword">return</span> &lt;返回值列表&gt;</span><br></pre></td></tr></table></figure>

<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">fact</span><span class="params">(n)</span> :</span></span><br><span class="line">    s = <span class="number">1</span></span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">1</span>, n+<span class="number">1</span>):</span><br><span class="line">        s *= i</span><br><span class="line">    <span class="keyword">return</span> s</span><br><span class="line"><span class="keyword">print</span> (fact(<span class="number">100</span>))</span><br></pre></td></tr></table></figure>

<p>使用步骤：</p>
<ol>
<li>函数定义；</li>
<li>函数调用；</li>
<li>函数执行；</li>
<li>函数返回</li>
</ol>
<h3 id="函数的参数传递"><a href="#函数的参数传递" class="headerlink" title="函数的参数传递"></a>函数的参数传递</h3><h4 id="可选参数传递"><a href="#可选参数传递" class="headerlink" title="可选参数传递"></a>可选参数传递</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> &lt;函数名&gt;<span class="params">(&lt;非可选参数&gt;, &lt;可选参数&gt; = &lt;默认值&gt;)</span> :</span></span><br><span class="line">    &lt;函数体&gt;</span><br><span class="line">    <span class="keyword">return</span></span><br></pre></td></tr></table></figure>

<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">multiply</span><span class="params">(x, y = <span class="number">10</span>)</span> :</span></span><br><span class="line">    print(x * y)</span><br><span class="line">mulitply(<span class="number">99</span>)</span><br><span class="line"><span class="comment"># 990</span></span><br><span class="line">multiply(<span class="number">99</span>, <span class="number">2</span>)</span><br><span class="line"><span class="comment"># 198</span></span><br></pre></td></tr></table></figure>

<h4 id="参数名称传递"><a href="#参数名称传递" class="headerlink" title="参数名称传递"></a>参数名称传递</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">multiply</span><span class="params">(x, y = <span class="number">10</span>)</span> :</span></span><br><span class="line">    print(x * y)</span><br><span class="line">multiply(x = <span class="number">99</span>)</span><br><span class="line"><span class="comment"># 990</span></span><br><span class="line">multiply(y = <span class="number">2</span>, x = <span class="number">99</span>)</span><br><span class="line"><span class="comment"># 198</span></span><br></pre></td></tr></table></figure>

<p><strong>不需要保持参数传递的顺序，参数之间的顺序可以任意调整。</strong></p>
<h3 id="函数的返回值"><a href="#函数的返回值" class="headerlink" title="函数的返回值"></a>函数的返回值</h3><p><strong>⭐return 语句用来结束函数并将程序返回到函数被调用的位置继续执行。</strong></p>
<p>return语句可以出现在函数中的任何部分，同时可以将0个、1个或多个函数运算的结果返回给函数被调用处的变量。</p>
<h3 id="变量的作用域"><a href="#变量的作用域" class="headerlink" title="变量的作用域"></a>变量的作用域</h3><h4 id="局部变量"><a href="#局部变量" class="headerlink" title="局部变量"></a>局部变量</h4><p>在函数内部定义的变量，仅在函数内部有效，当函数退出时变量将不再存在。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"> <span class="function"><span class="keyword">def</span> <span class="title">mul</span><span class="params">(x, y = <span class="number">10</span>)</span> :</span></span><br><span class="line">    z = x * y <span class="comment">#z是局部变量</span></span><br><span class="line">    <span class="keyword">return</span> z</span><br><span class="line">s = mul(<span class="number">99</span>, <span class="number">2</span>)</span><br><span class="line">print(s)</span><br><span class="line"><span class="comment"># 198</span></span><br><span class="line">print(z)</span><br><span class="line"><span class="comment"># error : ...</span></span><br></pre></td></tr></table></figure>

<h4 id="全局变量"><a href="#全局变量" class="headerlink" title="全局变量"></a>全局变量</h4><p>在函数之外定义的变量，在程序执行全过程有效。全局变量在函数内部使用时，需提前使用 global 声明。<code>global &lt;全局变量&gt;</code></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">n = <span class="number">2</span> <span class="comment">#n是全局变量</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">mul</span><span class="params">(x, y = <span class="number">10</span>)</span> :</span></span><br><span class="line">    <span class="keyword">global</span> n</span><br><span class="line">    <span class="keyword">return</span> x * y * n</span><br><span class="line">s = mul (<span class="number">99</span>, <span class="number">2</span>)</span><br><span class="line">print(s)</span><br><span class="line"><span class="number">396</span></span><br></pre></td></tr></table></figure>

<h3 id="代码复用"><a href="#代码复用" class="headerlink" title="代码复用"></a>代码复用</h3><p>好处：</p>
<ul>
<li>避免相同功能代码在被调用处重复编写；</li>
<li>当更新函数功能时，所有被调用处的功能都被更新。</li>
</ul>
<p>模块化设计：指通过函数的封装功能将程序划分为主程序、子程序和子程序间关系的表达。</p>
<p>模块化设计基本要求：</p>
<ul>
<li>紧耦合：尽可能合理划分功能块，功能块内部耦合紧密；</li>
<li>松耦合：模块间关系尽可能简单，功能块之间耦合度低。</li>
</ul>
<p>耦合性：指程序结构中各模块之间相互关联的程度，它取决于各模块间接口的复杂程度和调用方式。</p>
<ul>
<li>紧耦合：模块或系统间关系紧密，存在较多或复杂的相互调用。缺点：更新一个模块可能导致其他模块变化，复用较困难。</li>
<li>松耦合：一般基于消息或协议实现，系统间交互简单。</li>
</ul>
<h3 id="实例解析–软文的诗词风"><a href="#实例解析–软文的诗词风" class="headerlink" title="实例解析–软文的诗词风"></a>实例解析–软文的诗词风</h3><p>软文的诗词风将原有文章根据标点符号重新切分成短句并居中排版，对小屏幕阅读十分有利。使用程序将普通文章变成软文的诗词风十分有趣</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">txt = <span class="string">'''</span></span><br><span class="line"><span class="string">人生得意须尽欢，莫使金樽空对月。</span></span><br><span class="line"><span class="string">天生我材必有用，千金散尽还复来。</span></span><br><span class="line"><span class="string">'''</span></span><br><span class="line">linewidth = <span class="number">30</span>  <span class="comment"># 预定的输出宽度</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">lineSplit</span><span class="params">(line)</span>:</span></span><br><span class="line">    plist = [<span class="string">','</span>, <span class="string">'!'</span>, <span class="string">'?'</span>, <span class="string">'，'</span>, <span class="string">'。'</span>, <span class="string">'！'</span>, <span class="string">'？'</span>]</span><br><span class="line">    <span class="keyword">for</span> p <span class="keyword">in</span> plist:</span><br><span class="line">        line = line.replace(p, <span class="string">'\n'</span>)</span><br><span class="line">    <span class="keyword">return</span> line.split(<span class="string">'\n'</span>)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">linePrint</span><span class="params">(line)</span>:</span></span><br><span class="line">    <span class="keyword">global</span> linewidth</span><br><span class="line">    print(line.center(linewidth, chr(<span class="number">12288</span>)))</span><br><span class="line"></span><br><span class="line">newlines = lineSplit(txt)</span><br><span class="line"><span class="keyword">for</span> newline <span class="keyword">in</span> newlines:</span><br><span class="line">    linePrint(newline)</span><br></pre></td></tr></table></figure>

<h2 id="组合数据类型"><a href="#组合数据类型" class="headerlink" title="组合数据类型"></a>组合数据类型</h2><h3 id="组合数据类型基本概念"><a href="#组合数据类型基本概念" class="headerlink" title="组合数据类型基本概念"></a>组合数据类型基本概念</h3><p>能够表示多个数据的类型成为组合数据类型</p>
<ul>
<li>集合类型：元素集合，元素之间无序，相同元素在集合中唯一存在；</li>
<li>序列类型：元素向量，元素之间存在先后关系，通过序号访问，元素之间不排他；</li>
<li>映射类型：“键—值”数据项的组合，每个元素是一个键值对，表示为(key, value)。</li>
</ul>
<h4 id="集合类型概述"><a href="#集合类型概述" class="headerlink" title="集合类型概述"></a>集合类型概述</h4><p>包含0个或多个数据的无序组合，用大括号({})表示，集合中的元素可以动态增加或删除。</p>
<p>元素类型只能是不可变数据类型：整数、浮点数、字符串、元组等。</p>
<p>使用集合类型能够<strong>过滤重复元素</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">T = &#123;<span class="number">1010</span>, <span class="string">'1010'</span>, <span class="number">12.3</span>, <span class="number">1010</span>, <span class="number">1010</span>&#125;</span><br><span class="line">print(T)</span><br><span class="line"><span class="comment"># &#123;1010, '1010', 12.3&#125;</span></span><br></pre></td></tr></table></figure>

<table>
<thead>
<tr>
<th align="center">操作符及运算</th>
<th align="left">描述</th>
</tr>
</thead>
<tbody><tr>
<td align="center">S - T</td>
<td align="left">差集，返回一个新集合，包括在集合 S 中但不在集合 T 中的元素</td>
</tr>
<tr>
<td align="center">S &amp; T</td>
<td align="left">交集，返回一个新集合，包括同时在集合 S 和 T 中的元素</td>
</tr>
<tr>
<td align="center">S ^ T</td>
<td align="left">补集，返回一个新集合，包括集合 S 和 T 中非共同元素</td>
</tr>
<tr>
<td align="center">S | T</td>
<td align="left">并集，返回一个新集合，包括集合 S 和 T 中所有元素</td>
</tr>
</tbody></table>
<table>
<thead>
<tr>
<th align="center">函数或方法</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td align="center"><code>S.add(x)</code></td>
<td>如果数据项 x 不在集合 S 中，将 x 增加到 S</td>
</tr>
<tr>
<td align="center"><code>S.remove(x)</code></td>
<td>如果 x 在集合 S 中，移除 x；不在则产生 KeyError 异常</td>
</tr>
<tr>
<td align="center"><code>S.clear()</code></td>
<td>移除 S 中所有数据项</td>
</tr>
<tr>
<td align="center"><code>len(S)</code></td>
<td>返回集合 S 元素个数</td>
</tr>
<tr>
<td align="center"><code>x in S</code></td>
<td>如果 x 是 S 的元素，返回 True；否则 False</td>
</tr>
<tr>
<td align="center"><code>x not in S</code></td>
<td>如果 x 不是 S 的元素，返回 True；否则 False</td>
</tr>
</tbody></table>
<p>set(x) 函数将其他的组合数据类型变成集合类型，也可以生成空集合变量。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">S = set(<span class="string">'知之为知之不知为不知'</span>)</span><br><span class="line">print(S)</span><br><span class="line"><span class="comment"># &#123;'不', '为', '之', '知'&#125;</span></span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> S :</span><br><span class="line">    print(i, end = <span class="string">''</span>)</span><br><span class="line"><span class="comment"># 不为之知</span></span><br></pre></td></tr></table></figure>

<h4 id="序列类型概述"><a href="#序列类型概述" class="headerlink" title="序列类型概述"></a>序列类型概述</h4><p>序列类型是一维元素向量，元素之间存在先后关系，通过序号访问。</p>
<table>
<thead>
<tr>
<th align="center">操作符</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td align="center"><code>x in s</code></td>
<td>如果 x 是 s 的元素，返回 True，否则 False</td>
</tr>
<tr>
<td align="center"><code>x not in s</code></td>
<td>如果 x 不是 s 的元素，返回 True，否则 False</td>
</tr>
<tr>
<td align="center"><code>s + t</code></td>
<td>连接 s 和 t</td>
</tr>
<tr>
<td align="center"><code>s * n 或 n * s</code></td>
<td>将序列 s 复制 n 次</td>
</tr>
<tr>
<td align="center"><code>s[i]</code></td>
<td>索引，返回 s 的第 i 个元素</td>
</tr>
<tr>
<td align="center"><code>s[i : j]</code></td>
<td>切片，返回包含 s 第 i 到 j 个元素的子序列（不包含 j）</td>
</tr>
<tr>
<td align="center"><code>s[i : j : k]</code></td>
<td>步骤切片，返回包含 s 第 i 到 j 个元素以 k 为步数的子序列</td>
</tr>
<tr>
<td align="center"><code>len(s)</code></td>
<td>s 的元素个数（长度）</td>
</tr>
<tr>
<td align="center"><code>min(s)</code></td>
<td>s 中的最小元素</td>
</tr>
<tr>
<td align="center"><code>max(s)</code></td>
<td>s 中的最大元素</td>
</tr>
<tr>
<td align="center"><code>s.index(x)</code></td>
<td>s 中第一次出现元素 x 的位置</td>
</tr>
<tr>
<td align="center"><code>s.count(x)</code></td>
<td>s 中出现 x 的总次数</td>
</tr>
</tbody></table>
<h4 id="映射类型概述"><a href="#映射类型概述" class="headerlink" title="映射类型概述"></a>映射类型概述</h4><p>映射类型是“键-值”数据项的组合，每个元素是一个键值对，即元素是(key, value)，元素之间是无序的。键值对是一种二元关系，源于属性和值的映射关系</p>
<h3 id="列表类型"><a href="#列表类型" class="headerlink" title="列表类型"></a>列表类型</h3><h4 id="定义"><a href="#定义" class="headerlink" title="定义"></a>定义</h4><ul>
<li>列表是包含0个或多个元组的有序序列，属于序列类型。</li>
<li>可进行元素的增加、删除、替换、查找。</li>
<li>没有长度限制，元素类型可以不同，不需要预定长度。</li>
<li>列表类型用中括号(<code>[]</code>)，也可以通过<code>list()</code> 函数将集合或字符串类型转换成列表类型。</li>
</ul>
<p>列表属于序列类型，所以列表类型支持序列类型对应的操作</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">list(<span class="string">'举个栗子'</span>)</span><br><span class="line"><span class="comment"># ['举', '个', '栗', '子']</span></span><br></pre></td></tr></table></figure>

<h4 id="索引"><a href="#索引" class="headerlink" title="索引"></a>索引</h4><p>沿用序列类型的索引方式，即正向递增序号或反负递减序号，用中括号作为索引操作符，不得超过列表的元素范围，否则 IndexError。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">ls = [<span class="number">1010</span>, <span class="string">'1010'</span>, [<span class="number">1010</span>, <span class="string">'1010'</span>], <span class="number">1010</span>]</span><br><span class="line">ls = [<span class="number">3</span>]</span><br><span class="line"><span class="comment"># 1010</span></span><br><span class="line">ls[<span class="number">-2</span>]</span><br><span class="line"><span class="comment"># [1010, '1010']</span></span><br></pre></td></tr></table></figure>

<p>可以用<strong>遍历循环</strong>进行操作</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> &lt;循环变量&gt; <span class="keyword">in</span> &lt;列表变量&gt; :</span><br><span class="line">    &lt;语句块&gt;</span><br></pre></td></tr></table></figure>

<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">ls = [<span class="number">1010</span>, <span class="string">'1010'</span>, [<span class="number">1010</span>, <span class="string">'1010'</span>], <span class="number">1010</span>]</span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> ls :</span><br><span class="line">    print(i * <span class="number">2</span>)</span><br><span class="line"><span class="comment"># 2020</span></span><br><span class="line"><span class="comment"># 10101010</span></span><br><span class="line"><span class="comment"># [1010, '1010', 1010, '1010']</span></span><br><span class="line"><span class="comment"># 2020</span></span><br></pre></td></tr></table></figure>

<h4 id="切片"><a href="#切片" class="headerlink" title="切片"></a>切片</h4><p>切片后的结果也是列表类型</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;列表或列表变量&gt;[N : M]</span><br><span class="line">或</span><br><span class="line">&lt;列表或列表变量&gt;[N : M : K]</span><br></pre></td></tr></table></figure>

<p>在 [ ] 中表示区间需要用冒号（:），表示枚举使用英文逗号</p>
<p>一般要求 N 小于 M，当 N 大于 M 时，返回空列表</p>
<h3 id="列表类型的操作"><a href="#列表类型的操作" class="headerlink" title="列表类型的操作"></a>列表类型的操作</h3><h4 id="操作函数"><a href="#操作函数" class="headerlink" title="操作函数"></a>操作函数</h4><table>
<thead>
<tr>
<th align="center">函数</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td align="center"><code>len(ls)</code></td>
<td>列表 ls 的元素个数（长度）</td>
</tr>
<tr>
<td align="center"><code>min(ls)</code></td>
<td>ls 中的最小元素</td>
</tr>
<tr>
<td align="center"><code>max(ls)</code></td>
<td>ls 中的最大元素</td>
</tr>
<tr>
<td align="center"><code>list(x)</code></td>
<td>将 x 转变成列表类型</td>
</tr>
</tbody></table>
<h4 id="列表的操作方法"><a href="#列表的操作方法" class="headerlink" title="列表的操作方法"></a>列表的操作方法</h4><p><code>&lt;列表变量&gt;.&lt;方法名称&gt;(&lt;方法参数&gt;)</code></p>
<table>
<thead>
<tr>
<th align="center">方法</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td align="center"><code>ls.append(x)</code></td>
<td>在 ls 最后增加 x</td>
</tr>
<tr>
<td align="center"><code>ls.insert(i, x)</code></td>
<td>在 ls 第 i 位置增加 x</td>
</tr>
<tr>
<td align="center"><code>ls.clear()</code></td>
<td>删除 ls 中所有元素</td>
</tr>
<tr>
<td align="center"><code>ls.pop(i)</code></td>
<td>将 ls 中第 i 项元素取出并从 ls  中删除</td>
</tr>
<tr>
<td align="center"><code>ls.remove(x)</code></td>
<td>将 ls 中出现的第一个 x 删除</td>
</tr>
<tr>
<td align="center"><code>ls.reverse()</code></td>
<td>ls 中元素反转</td>
</tr>
<tr>
<td align="center"><code>ls.copy()</code></td>
<td>生成新列表，复制 ls</td>
</tr>
</tbody></table>
<p><strong>del</strong>对列表元素或片段进行删除，使用方法如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">del</span> &lt;列表变量&gt;[&lt;索引序号&gt;] 或</span><br><span class="line"><span class="keyword">del</span> &lt;列表变量&gt;[&lt;索引起始&gt;: &lt;索引结束&gt;]</span><br></pre></td></tr></table></figure>

<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">ls = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>]</span><br><span class="line"><span class="keyword">del</span> ls[<span class="number">1</span>]</span><br><span class="line">print(ls)</span><br><span class="line"><span class="comment"># [1, 3, 4]</span></span><br></pre></td></tr></table></figure>

<p><strong>ls.copy()</strong> 生成的新列表不受旧列表影响</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">ls = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>]</span><br><span class="line">lsn = ls.copy()</span><br><span class="line">ls.clear()</span><br><span class="line">print(lsn)</span><br><span class="line"><span class="comment"># [1, 2, 3, 4]</span></span><br><span class="line"></span><br><span class="line">lt = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>]</span><br><span class="line">ls = lt</span><br><span class="line">lt.clear()</span><br><span class="line">print(ls)</span><br><span class="line"><span class="comment"># []</span></span><br></pre></td></tr></table></figure>

<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">main</span><span class="params">()</span>:</span></span><br><span class="line">    list1 = list(range(<span class="number">1</span>, <span class="number">8</span>, <span class="number">2</span>))</span><br><span class="line">    list1.append(<span class="number">100</span>)</span><br><span class="line">    print(list1)  <span class="comment"># [1, 3, 5, 7, 100]</span></span><br><span class="line">    list2 = [<span class="string">'hello'</span>] * <span class="number">5</span>  </span><br><span class="line">    print(list2)  <span class="comment"># ['hello', 'hello', 'hello', 'hello', 'hello']</span></span><br><span class="line">    <span class="comment"># 计算列表长度(元素个数)</span></span><br><span class="line">    print(len(list1))  <span class="comment"># 5</span></span><br><span class="line">    <span class="comment"># 下标(索引)运算，访问列表</span></span><br><span class="line">    print(list1[<span class="number">0</span>])  <span class="comment"># 1</span></span><br><span class="line">    print(list1[<span class="number">4</span>])  <span class="comment"># 100</span></span><br><span class="line">    print(list1[<span class="number">5</span>])  <span class="comment"># IndexError: list index out of range</span></span><br><span class="line">    print(list1[<span class="number">-1</span>])  <span class="comment"># 100</span></span><br><span class="line">    print(list1[<span class="number">-3</span>])  <span class="comment"># 5</span></span><br><span class="line">    <span class="comment"># 替换元素</span></span><br><span class="line">    list1[<span class="number">2</span>] = <span class="number">300</span></span><br><span class="line">    print(list1)  <span class="comment"># [1, 3, 300, 7, 100]</span></span><br><span class="line">    <span class="comment"># 添加元素</span></span><br><span class="line">    list1.append(<span class="number">200</span>)  <span class="comment"># 添加到尾部</span></span><br><span class="line">    list1.insert(<span class="number">1</span>, <span class="number">400</span>)  <span class="comment"># 插入到对应索引号</span></span><br><span class="line">    list1 += [<span class="number">1000</span>, <span class="number">2000</span>]  <span class="comment"># 添加到尾部</span></span><br><span class="line">    print(list1)</span><br><span class="line">    print(len(list1))</span><br><span class="line">    <span class="comment"># 删除元素</span></span><br><span class="line">    <span class="keyword">del</span> list1[<span class="number">0</span>]  <span class="comment"># 删除对应索引号的元素</span></span><br><span class="line">    print(list1)</span><br><span class="line">    print(list1.pop())  <span class="comment"># 弹出末尾元素，括号内输入索引值便可弹出对应元素</span></span><br><span class="line">    print(list1)</span><br><span class="line">    list1.remove(<span class="number">3</span>)  <span class="comment"># 根据值删除元素，只删除第一个指定的值</span></span><br><span class="line">    <span class="keyword">if</span> <span class="number">1234</span> <span class="keyword">in</span> list1:  <span class="comment"># 进行优化</span></span><br><span class="line">        list1.remove(<span class="number">1234</span>)</span><br><span class="line">    <span class="keyword">del</span> list1[<span class="number">0</span>]</span><br><span class="line">    print(list1)</span><br><span class="line">    <span class="comment"># 清空列表元素</span></span><br><span class="line">    <span class="comment"># list1 = []</span></span><br><span class="line">    list2 = list1</span><br><span class="line">    list1.clear()  <span class="comment"># 采用clear函数清理关联列表</span></span><br><span class="line">    print(list1)</span><br><span class="line">    print(list2)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</span><br><span class="line">    main()</span><br></pre></td></tr></table></figure>

<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">main</span><span class="params">()</span>:</span></span><br><span class="line">    list1 = [<span class="string">'orange'</span>, <span class="string">'apple'</span>, <span class="string">'zoo'</span>, <span class="string">'internationalization'</span>, <span class="string">'blueberry'</span>]</span><br><span class="line">    <span class="comment"># sorted函数返回列表排序后的拷贝不会修改传入的列表</span></span><br><span class="line">    list2 = sorted(list1)</span><br><span class="line">    <span class="comment"># 函数的设计就应该像sorted函数一样尽可能不产生副作用</span></span><br><span class="line">    list3 = sorted(list1, reverse=<span class="literal">True</span>)</span><br><span class="line">    <span class="comment"># 通过key关键字参数指定根据字符串长度进行排序而不是默认的字母表顺序</span></span><br><span class="line">    list4 = sorted(list1, key=len)</span><br><span class="line">    print(list1)</span><br><span class="line">    print(list2)</span><br><span class="line">    print(list3)</span><br><span class="line">    print(list4)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 给列表对象发出排序消息直接在列表对象上进行排序</span></span><br><span class="line">    list1.sort(reverse=<span class="literal">True</span>)  <span class="comment"># 参数reverse=True按字母反向排序</span></span><br><span class="line">    list1.reverse()  <span class="comment"># 反转列表</span></span><br><span class="line">    <span class="comment"># list1[::-1]</span></span><br><span class="line">    print(list1)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</span><br><span class="line">    main()</span><br></pre></td></tr></table></figure>

<h3 id="字典的索引"><a href="#字典的索引" class="headerlink" title="字典的索引"></a>字典的索引</h3><p><code>&lt;值&gt; = &lt;字典变量&gt;[&lt;键&gt;]</code></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">d = &#123;<span class="string">'20101'</span>:<span class="string">'小明'</span>, <span class="string">'20102'</span>:<span class="string">'小红'</span>, <span class="string">'20103'</span>:<span class="string">'小白'</span>&#125;</span><br><span class="line">print(d[<span class="string">'20102'</span>])</span><br><span class="line"><span class="comment"># 小红</span></span><br></pre></td></tr></table></figure>

<p>大括号 { } 可以创建字典，索引和赋值可以增加元素。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">t = &#123;&#125;</span><br><span class="line">t[<span class="string">'20104'</span>:<span class="string">'小新'</span>]</span><br><span class="line">print(t)</span><br><span class="line"><span class="comment"># &#123;'20104':'小新'&#125;</span></span><br></pre></td></tr></table></figure>

<p>字典是存储可变数量键值对的数据结构，<strong>键和值可以是任意数据类型</strong>。</p>
<p><strong>键必须是不可变的</strong>，如字符串，数字或元组。</p>
<h3 id="字典的操作"><a href="#字典的操作" class="headerlink" title="字典的操作"></a>字典的操作</h3><h4 id="相关操作函数"><a href="#相关操作函数" class="headerlink" title="相关操作函数"></a>相关操作函数</h4><table>
<thead>
<tr>
<th align="center">函数</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td align="center"><code>len(d)</code></td>
<td>字典 d 的元素个数（长度）</td>
</tr>
<tr>
<td align="center"><code>min(d)</code></td>
<td>字典 d 中键的最小值</td>
</tr>
<tr>
<td align="center"><code>max(d)</code></td>
<td>字典 d 中键的最大值</td>
</tr>
<tr>
<td align="center"><code>dict()</code></td>
<td>生成一个空字典</td>
</tr>
</tbody></table>
<h4 id="操作方法"><a href="#操作方法" class="headerlink" title="操作方法"></a>操作方法</h4><p><code>&lt;字典变量&gt;.&lt;方法名称&gt;(&lt;方法参数&gt;)</code></p>
<table>
<thead>
<tr>
<th align="center">方法</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td align="center"><code>d.keys()</code></td>
<td>返回所有的键信息</td>
</tr>
<tr>
<td align="center"><code>d.values()</code></td>
<td>返回所有的值信息</td>
</tr>
<tr>
<td align="center"><code>d.items()</code></td>
<td>返回所有的键值对</td>
</tr>
<tr>
<td align="center"><code>d.get(key, default)</code></td>
<td>键存在则返回相应值，否则返回默认值</td>
</tr>
<tr>
<td align="center"><code>d.pop(key, default)</code></td>
<td>键存在则返回并删除值对，否则返回默认值</td>
</tr>
<tr>
<td align="center"><code>d.popitem()</code></td>
<td>随机从字典中去取出一个键值对，以元组(key, value)形式返回，并从字典中删除</td>
</tr>
<tr>
<td align="center"><code>d.clear()</code></td>
<td>删除所有的键值对</td>
</tr>
</tbody></table>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">d = &#123;<span class="string">'1'</span>:<span class="string">'A'</span>, <span class="string">'2'</span>:<span class="string">'B'</span>, <span class="string">'3'</span>:<span class="string">'C'</span>&#125;</span><br><span class="line">d.items()</span><br><span class="line"><span class="comment"># dict_items([('1','A'), ('2', 'B'), ('3', 'C')])</span></span><br><span class="line"></span><br><span class="line">d.get(<span class="string">'4'</span>)</span><br><span class="line"></span><br><span class="line">d.get(<span class="string">'4'</span>, <span class="string">'不存在'</span>)</span><br><span class="line"><span class="comment"># '不存在'</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">del</span> d[<span class="string">'1'</span>]</span><br><span class="line">print(d)</span><br><span class="line"><span class="comment"># &#123;'2':'B', '3':'C'&#125;</span></span><br><span class="line"></span><br><span class="line"><span class="string">'1'</span> <span class="keyword">in</span> d</span><br><span class="line"><span class="comment"># True</span></span><br><span class="line"></span><br><span class="line"><span class="string">'4'</span> <span class="keyword">in</span> d</span><br><span class="line"><span class="comment"># False</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> k <span class="keyword">in</span> d:</span><br><span class="line">    print(<span class="string">'The key and value are &#123;&#125; and &#123;&#125;'</span>.format(k, d.get(k)))</span><br><span class="line"><span class="comment"># The key and value are 1 and A</span></span><br><span class="line"><span class="comment"># The key and value are 2 and B</span></span><br><span class="line"><span class="comment"># The key and value are 3 and C</span></span><br></pre></td></tr></table></figure>

<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">main</span><span class="params">()</span>:</span></span><br><span class="line">    scores = &#123;<span class="string">'骆昊'</span>: <span class="number">95</span>, <span class="string">'白元芳'</span>: <span class="number">78</span>, <span class="string">'狄仁杰'</span>: <span class="number">82</span>&#125;</span><br><span class="line">    <span class="comment"># 通过键可以获取字典中对应的值</span></span><br><span class="line">    print(scores[<span class="string">'骆昊'</span>])</span><br><span class="line">    print(scores[<span class="string">'狄仁杰'</span>])</span><br><span class="line">    <span class="comment"># 对字典进行遍历(遍历的其实是键再通过键取对应的值)</span></span><br><span class="line">    <span class="keyword">for</span> elem <span class="keyword">in</span> scores:</span><br><span class="line">        print(<span class="string">'%s\t---&gt;\t%d'</span> % (elem, scores[elem]))</span><br><span class="line">    <span class="comment"># 更新字典中的元素</span></span><br><span class="line">    scores[<span class="string">'白元芳'</span>] = <span class="number">65</span></span><br><span class="line">    scores[<span class="string">'诸葛王朗'</span>] = <span class="number">71</span></span><br><span class="line">    scores.update(冷面=<span class="number">67</span>, 方启鹤=<span class="number">85</span>)</span><br><span class="line">    print(scores)</span><br><span class="line">    <span class="keyword">if</span> <span class="string">'武则天'</span> <span class="keyword">in</span> scores:</span><br><span class="line">        print(scores[<span class="string">'武则天'</span>])</span><br><span class="line">    print(scores.get(<span class="string">'武则天'</span>))</span><br><span class="line">    <span class="comment"># get方法也是通过键获取对应的值但是可以设置默认值</span></span><br><span class="line">    print(scores.get(<span class="string">'武则天'</span>, <span class="number">60</span>))</span><br><span class="line">    <span class="comment"># 删除字典中的元素</span></span><br><span class="line">    print(scores.popitem())</span><br><span class="line">    print(scores.popitem())</span><br><span class="line">    print(scores.pop(<span class="string">'骆昊'</span>, <span class="number">100</span>))</span><br><span class="line">    <span class="comment"># 清空字典</span></span><br><span class="line">    scores.clear()</span><br><span class="line">    print(scores)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</span><br><span class="line">    main()</span><br></pre></td></tr></table></figure>

<h3 id="实例解析——文本词频统计"><a href="#实例解析——文本词频统计" class="headerlink" title="实例解析——文本词频统计"></a>实例解析——文本词频统计</h3><p>在很多情况下，会遇到这样的问题：对于一篇给定文章，希望统计其中多次出现的词语，进而概要分析文章的内容。这个问题的解决可用于对网络信息进行自动检索和归档。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">'''</span></span><br><span class="line"><span class="string">第一步：分解并提取英文文章的单词通过txt.lower()函数将字母变成小写，排除原文大小写差异对词频统计的干扰。为统一分隔方式，可以将各种特殊字符和标点符号使用txt.replace()方法替换成空格，再提取单词。</span></span><br><span class="line"><span class="string">'''</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">getText</span><span class="params">()</span>:</span></span><br><span class="line">    txt = open(<span class="string">'hamlet.txt'</span>, <span class="string">'r'</span>).read()</span><br><span class="line">    txt = txt.lower()</span><br><span class="line">    <span class="keyword">for</span> ch <span class="keyword">in</span> <span class="string">'!"#$&amp;%()*+,-./:;&lt;=&gt;?@[\\]^_&#123;|&#125;~'</span>:</span><br><span class="line">        txt = txt.replace(ch, <span class="string">''</span>)</span><br><span class="line">    <span class="keyword">return</span> txt</span><br><span class="line"></span><br><span class="line">hamletTxt = getText()</span><br><span class="line">words = hamletTxt.split()</span><br><span class="line">counts = &#123;&#125;</span><br><span class="line"><span class="string">'''</span></span><br><span class="line"><span class="string">第二步：对每个单词进行计数</span></span><br><span class="line"><span class="string">或者，这个处理逻辑可以更简洁的表示为如下代码：</span></span><br><span class="line"><span class="string">counts[word] = counts.get(word,0) + 1</span></span><br><span class="line"><span class="string">'''</span></span><br><span class="line"><span class="keyword">for</span> word <span class="keyword">in</span> words:</span><br><span class="line">    counts[word] = count.get(word, <span class="number">0</span>) + <span class="number">1</span></span><br><span class="line"><span class="string">'''</span></span><br><span class="line"><span class="string">对单词的统计值从高到低进行排序由于字典类型没有顺序，</span></span><br><span class="line"><span class="string">需要将其转换为有顺序的列表类型，</span></span><br><span class="line"><span class="string">再使用sort()方法和lambda函数配合实现根据单词次数对元素进行排序。</span></span><br><span class="line"><span class="string">'''</span></span><br><span class="line">items = list(counts.items()) <span class="comment"># 将字典转换为记录列表</span></span><br><span class="line">items.sort(key = <span class="keyword">lambda</span> x:x[<span class="number">1</span>], reverse = <span class="literal">True</span>) <span class="comment"># 以第2列排序</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">10</span>):</span><br><span class="line">    word, count = items[i]</span><br><span class="line">    print(<span class="string">'&#123;0:&lt;10&#125;&#123;1:&gt;5&#125;'</span>.format(word, count))</span><br></pre></td></tr></table></figure>

<h2 id="文件和数据格式化"><a href="#文件和数据格式化" class="headerlink" title="文件和数据格式化"></a>文件和数据格式化</h2><h3 id="文件的使用"><a href="#文件的使用" class="headerlink" title="文件的使用"></a>文件的使用</h3><p>两种类型：文本文件、二进制文件</p>
<p>存储在辅助存储器上的一组数据序列。</p>
<h4 id="文件的类型"><a href="#文件的类型" class="headerlink" title="文件的类型"></a>文件的类型</h4><p>文本文件：由单一特定编码的字符组成；</p>
<p>二进制文件：直接由比特0和比特1组成，没有统一的字符编码，文件内部数据的组织格式与文件用途有关。</p>
<h4 id="打开和关闭"><a href="#打开和关闭" class="headerlink" title="打开和关闭"></a>打开和关闭</h4><p>文件的存储状态是默认状态，打开后变成占用状态，关闭后再次回到存储状态。</p>
<p><code>open()</code>函数：打开一个文件，并返回一个操作这个文件的变量</p>
<p><code>&lt;变量名&gt; = open(&lt;文件路径及文件名&gt;, &lt;打开模式&gt;)</code></p>
<table>
<thead>
<tr>
<th align="center">打开模式</th>
<th>含义</th>
</tr>
</thead>
<tbody><tr>
<td align="center"><code>&#39;r&#39;</code></td>
<td>只读，如果文件不存在返回异常 FileNotFoundError，默认值</td>
</tr>
<tr>
<td align="center"><code>&#39;w&#39;</code></td>
<td>覆盖写，文件不存在则创建，存在则完全覆盖原文件</td>
</tr>
<tr>
<td align="center"><code>&#39;x&#39;</code></td>
<td>创建写，文件不存在则创建，存在则返回异常 FileExistsError</td>
</tr>
<tr>
<td align="center"><code>&#39;a&#39;</code></td>
<td>追加写，文件不存在则创建，存在则在源文件最后追加内容</td>
</tr>
<tr>
<td align="center"><code>&#39;b&#39;</code></td>
<td>二进制文件模式</td>
</tr>
<tr>
<td align="center"><code>&#39;t&#39;</code></td>
<td>文本文件模式，默认值</td>
</tr>
<tr>
<td align="center"><code>&#39;+&#39;</code></td>
<td>与 r w x d 一同使用，在原功能上增加读写功能</td>
</tr>
</tbody></table>
<p>&lt;变量名&gt;.close() 关闭文件，释放文件的使用授权。</p>
<p>*<em>表示路径时，使用 <code>\\\</code> 或 / 代替  <code>\\</code> *</em></p>
<h4 id="文件的读写"><a href="#文件的读写" class="headerlink" title="文件的读写"></a>文件的读写</h4><table>
<thead>
<tr>
<th align="center">读取方法</th>
<th>含义</th>
</tr>
</thead>
<tbody><tr>
<td align="center"><code>f.read(size = -1)</code></td>
<td>从文件中读入整个文件内容。参数可选，读入前size长度的字符串或字节流</td>
</tr>
<tr>
<td align="center"><code>f.readline(size = -1)</code></td>
<td>从文件中读入一行内容。参数可选，读入该行前size长度的字符串或字节流</td>
</tr>
<tr>
<td align="center"><code>f.readlines(hint  = -1)</code></td>
<td>从文件中读入所有行，以每行为元素形成一个列表。参数可选，读入 hint 行</td>
</tr>
<tr>
<td align="center"><code>f.seek(offset)</code></td>
<td>改变当前文件操作指针的位置。offset : 0为文件开头；2为文件结尾</td>
</tr>
</tbody></table>
<table>
<thead>
<tr>
<th align="center">写入方法</th>
<th>含义</th>
</tr>
</thead>
<tbody><tr>
<td align="center"><code>f.write(s)</code></td>
<td>向文件写入一个字符串或字节流</td>
</tr>
<tr>
<td align="center"><code>f.writelines(s)</code></td>
<td>将一个元素为字符串的列表整体写入文件</td>
</tr>
</tbody></table>
<p>f.write(s) 写入字符串 s，每次写入后，将会记录一个<strong>写入指针</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">f = open(<span class="string">'d:/c.txt'</span>, <span class="string">'w'</span>)</span><br><span class="line">f.write(<span class="string">'123\n'</span>)</span><br><span class="line">f.write(<span class="string">'456\n'</span>)</span><br><span class="line">f.close()</span><br></pre></td></tr></table></figure>

<p>要显式地<strong>使用<code>\n</code>进行分行</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">ls = [<span class="string">'123'</span>, <span class="string">'456'</span>, <span class="string">'789'</span>]</span><br><span class="line">f = open(<span class="string">'d:/d.txt'</span>, <span class="string">'w'</span>)</span><br><span class="line">f.writelinese(ls)</span><br><span class="line">f.close()</span><br></pre></td></tr></table></figure>

<h3 id="数据组织的维度"><a href="#数据组织的维度" class="headerlink" title="数据组织的维度"></a>数据组织的维度</h3><h4 id="一维数据"><a href="#一维数据" class="headerlink" title="一维数据"></a>一维数据</h4><p>由对等关系的有序或无序数据构成，采用线性方式组织。</p>
<p>任何表现为序列或集合的内容都可以看作是一维数据。</p>
<h4 id="二维数据"><a href="#二维数据" class="headerlink" title="二维数据"></a>二维数据</h4><p>也称表格数据，由关联系数构成，采用二维表格方式组成。</p>
<h4 id="高维数据"><a href="#高维数据" class="headerlink" title="高维数据"></a>高维数据</h4><p>由键值对类型的数据组成，采用对象方式组织，可以多层嵌套。</p>
<p>高维数据在Web系统中十分常用，作为当今Internet组织内容的主要方式，高位数据衍生出HTML、XML、JSON等具体数据组织的语法结构。</p>
<h3 id="一维数据处理"><a href="#一维数据处理" class="headerlink" title="一维数据处理"></a>一维数据处理</h3><h4 id="表示"><a href="#表示" class="headerlink" title="表示"></a>表示</h4><p>由于是线性结构，因此主要采用列表形式表示。</p>
<h4 id="存储"><a href="#存储" class="headerlink" title="存储"></a>存储</h4><p>4种方法：</p>
<ol>
<li>采用空格分隔元素：A 12 数据</li>
<li>采用逗号分隔元素：A, 12, 数据</li>
<li>采用续行分隔元素：A<pre><code>12
数据</code></pre></li>
<li>其他特殊符号分隔，如分号：A; 12; 数据</li>
</ol>
<p>逗号分隔的存储格式为 CSV 格式（Comma_Separated Values），它是<strong>一种通用的、相对简单的文件格式</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">ls = [<span class="string">'北京'</span>, <span class="string">'上海'</span>, <span class="string">'广州'</span>]</span><br><span class="line">f = open(<span class="string">'city.csv'</span>, <span class="string">'w'</span>)</span><br><span class="line">f.write(<span class="string">','</span>.join(ls) + <span class="string">'\n'</span>)</span><br><span class="line">f.close()</span><br></pre></td></tr></table></figure>

<h4 id="处理"><a href="#处理" class="headerlink" title="处理"></a>处理</h4><p>首先需要从 CSV 文件读入一维数据，并将其表示为列表对象。</p>
<p>默认包含了一个换行符 <code>\n</code>。<strong>采用 <code>.strip()</code> 去掉</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">f = open(<span class="string">'city.csv'</span>, <span class="string">'r'</span>)</span><br><span class="line">ls = f.read().strip(<span class="string">'\n'</span>).split(<span class="string">','</span>)</span><br><span class="line">f.close()</span><br><span class="line">print(ls)</span><br></pre></td></tr></table></figure>

<h3 id="二维数据的处理"><a href="#二维数据的处理" class="headerlink" title="二维数据的处理"></a>二维数据的处理</h3><h4 id="表示方法"><a href="#表示方法" class="headerlink" title="表示方法"></a>表示方法</h4><p>二维数据可以采用二维列表来表示。</p>
<p>二维数据一般采用相同的数据类型存储</p>
<h4 id="存储方式"><a href="#存储方式" class="headerlink" title="存储方式"></a>存储方式</h4><p>用 csv 文件存储</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># ls 代表二维列表</span></span><br><span class="line">f = open(<span class="string">'cpi.csv'</span>, <span class="string">'w'</span>)</span><br><span class="line"><span class="keyword">for</span> row <span class="keyword">in</span> ls:</span><br><span class="line">    f.wrtie(<span class="string">','</span>.join(row) + <span class="string">'\n'</span>)</span><br><span class="line">f.close()</span><br></pre></td></tr></table></figure>

<h4 id="处理代码"><a href="#处理代码" class="headerlink" title="处理代码"></a>处理代码</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">f = open(<span class="string">'cpi.csv'</span>, <span class="string">'r'</span>)</span><br><span class="line">ls = []</span><br><span class="line"><span class="keyword">for</span> line <span class="keyword">in</span> f :</span><br><span class="line">    ls.append(line.strip(<span class="string">'\n'</span>).split(<span class="string">','</span>))</span><br><span class="line">f.close()</span><br><span class="line">print(ls)</span><br></pre></td></tr></table></figure>

<p>与一维列表不同，二维列表一般需要借助<strong>循环遍历</strong>实现对每个数据的处理</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> row <span class="keyword">in</span> ls :</span><br><span class="line">    <span class="keyword">for</span> item <span class="keyword">in</span> row:</span><br><span class="line">对第 row 行第 item 列元素进行处理</span><br></pre></td></tr></table></figure>

<p>对二维数据进行格式化输出，打印成表格形状：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#此出省去从 CSV 获得的 ls</span></span><br><span class="line"><span class="keyword">for</span> row <span class="keyword">in</span> ls:</span><br><span class="line">    line = <span class="string">''</span></span><br><span class="line">    <span class="keyword">for</span> item <span class="keyword">in</span> row:</span><br><span class="line">        line += <span class="string">'&#123;:10&#125;\t'</span>.format(item) <span class="comment">#\t 横行制表符</span></span><br><span class="line">    print(line)</span><br></pre></td></tr></table></figure>

<h4 id="zip-函数"><a href="#zip-函数" class="headerlink" title="zip()函数"></a><code>zip()</code>函数</h4><p>用来获取两个组合数据类，并将它的元素交织返回</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">x = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>]</span><br><span class="line">y = [<span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>]</span><br><span class="line">print(zip(x, y))</span><br><span class="line"><span class="comment"># [(1, 4), (2, 5), (3, 6)]</span></span><br></pre></td></tr></table></figure>

<h3 id="实例解析–国家财政数据趋势演算"><a href="#实例解析–国家财政数据趋势演算" class="headerlink" title="实例解析–国家财政数据趋势演算"></a>实例解析–国家财政数据趋势演算</h3><p>由个别数据预测规律属于数值分析的内容，可以通过线性回归方程建立简单模型，</p>
<p>线性回归方程的公式为： $\hat y$ = b$\hat x$ + a</p>
<p>X代表年份，Y代表各年份对应的数值。Python实现的国家财政数据趋势演算，根据上述三个数值计算出更多年份的可能数据。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">means</span><span class="params">(data)</span>:</span></span><br><span class="line">    <span class="keyword">return</span> sum(data) / len(data)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">linearRegression</span><span class="params">(xlist, ylist)</span>:</span></span><br><span class="line">    xmeans, ymeans = means(xlist), means(ylist)</span><br><span class="line">    bNumerator = -len(xlist) * xmeans * ymeans</span><br><span class="line">    bDenominator = -len(xlist) * xmeans ** <span class="number">2</span></span><br><span class="line">    <span class="keyword">for</span> x, y <span class="keyword">in</span> zip(xlist, ylist):</span><br><span class="line">        bNumerator += x * y</span><br><span class="line">        bDenominator += x ** <span class="number">2</span></span><br><span class="line">    b = bNumerator / bDenominator</span><br><span class="line">    a = ymeas - b * xmeans</span><br><span class="line">    <span class="keyword">return</span> a, b</span><br></pre></td></tr></table></figure>

<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">parseCSV</span><span class="params">(filename)</span>:</span></span><br><span class="line">    dataNames, data = [], []</span><br><span class="line">    f = open(filename, <span class="string">'r'</span>, encoding=<span class="string">'utf-8'</span>)</span><br><span class="line">    <span class="keyword">for</span> line <span class="keyword">in</span> f:</span><br><span class="line">        splitedLine = line.strip().split(<span class="string">','</span>)</span><br><span class="line">        <span class="keyword">if</span> <span class="string">'指标'</span> <span class="keyword">in</span> splitedLine[<span class="number">0</span>]:</span><br><span class="line">            years = [int(x[:<span class="number">-1</span>]) <span class="keyword">for</span> x <span class="keyword">in</span> splitedLine[<span class="number">1</span>:]]</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            dataNames.append(<span class="string">'&#123;:10&#125;'</span>.format(splitedLine[<span class="number">0</span>]))</span><br><span class="line">            data.append([float(x) <span class="keyword">for</span> x <span class="keyword">in</span> splitedLine[<span class="number">1</span>:]])</span><br><span class="line">    f.close()</span><br><span class="line">    <span class="keyword">return</span> years, dataNames, data</span><br><span class="line"><span class="comment"># 线性回归代码</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">means</span><span class="params">(data)</span>:</span></span><br><span class="line">    <span class="keyword">return</span> sum(data) / len(data)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">linearRegression</span><span class="params">(xlist, ylist)</span>:</span></span><br><span class="line">    xmeans, ymeans = means(xlist), means(ylist)</span><br><span class="line">    bNumerator = - len(xlist) * xmeans * ymeans</span><br><span class="line">    bDenominator =  - len(xlist) * xmeans ** <span class="number">2</span></span><br><span class="line">    <span class="keyword">for</span> x, y <span class="keyword">in</span> zip(xlist, ylist):</span><br><span class="line">        bNumerator += x * y</span><br><span class="line">        bDenominator += x ** <span class="number">2</span></span><br><span class="line">    b = bNumerator / bDenominator</span><br><span class="line">    a = ymeans - b * xmeans</span><br><span class="line">    <span class="keyword">return</span> a, b</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">calNewData</span><span class="params">(newyears, a, b)</span>:</span></span><br><span class="line">    <span class="keyword">return</span> [(a + b * x) <span class="keyword">for</span> x <span class="keyword">in</span> newyears]</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">showResults</span><span class="params">(years, dataNames, newDatas)</span>:</span></span><br><span class="line">    print(<span class="string">'&#123;:^60&#125;'</span>.format(<span class="string">'国家财政收支线性估计'</span>))</span><br><span class="line">    header = <span class="string">'指标       '</span></span><br><span class="line">    <span class="keyword">for</span> year <span class="keyword">in</span> years:</span><br><span class="line">        header += <span class="string">'&#123;:10&#125;'</span>.format(year)</span><br><span class="line">    print(header)</span><br><span class="line">    <span class="keyword">for</span> name, lineData <span class="keyword">in</span> zip(dataNames, newDatas):</span><br><span class="line">        line = name</span><br><span class="line">        <span class="keyword">for</span> data <span class="keyword">in</span> lineData:</span><br><span class="line">            line += <span class="string">'&#123;:&gt;10.1f&#125;'</span>.format(data)</span><br><span class="line">        print(line)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">main</span><span class="params">()</span>:</span></span><br><span class="line">    newyears = [x+<span class="number">2010</span> <span class="keyword">for</span> x <span class="keyword">in</span> range(<span class="number">7</span>)]</span><br><span class="line">    newDatas = []</span><br><span class="line">    years, dataNames, datas = parseCSV(<span class="string">'finance.csv'</span>)</span><br><span class="line">    <span class="keyword">for</span> data <span class="keyword">in</span> datas:</span><br><span class="line">        a, b = linearRegression(years, data)</span><br><span class="line">        newDatas.append(calNewData(newyears, a, b))</span><br><span class="line">    showResults(newyears, dataNames, newDatas)</span><br><span class="line"></span><br><span class="line">main()</span><br></pre></td></tr></table></figure>

<h2 id="Python-计算生态"><a href="#Python-计算生态" class="headerlink" title="Python 计算生态"></a>Python 计算生态</h2><h3 id="计算思维"><a href="#计算思维" class="headerlink" title="计算思维"></a>计算思维</h3><p>程序设计是实践计算思维的重要手段</p>
<p>本质：抽象和自动化</p>
<p>算法（Algorithm）：<strong>解决问题的清晰指令</strong></p>
<h3 id="程序设计方法论"><a href="#程序设计方法论" class="headerlink" title="程序设计方法论"></a>程序设计方法论</h3><p>一个解决复杂问题行之有效的方法被称作自顶而下的设计方法，其基本思想是以一个总问题开始，试图把它表达为很多小问题组成的解决方案。再用同样的技术依次攻破每个小问题，最终问题变得非常小，以至于可以很容易解决。然后只需把所有的碎片组合起来，就可以得到一个程序。</p>
<h4 id="自顶向下设计：最重要是顶层设计"><a href="#自顶向下设计：最重要是顶层设计" class="headerlink" title="自顶向下设计：最重要是顶层设计"></a>自顶向下设计：最重要是顶层设计</h4><p>是一种开发复杂程序最具价值的设计理念和工具，设计过程自然且简单，自顶向下设计通过封装实现抽象，利用了模块化设计的思想。</p>
<h4 id="自底向上执行"><a href="#自底向上执行" class="headerlink" title="自底向上执行"></a>自底向上执行</h4><p>开展测试的更好办法也是将程序分成小部分逐个测试</p>
<p>执行中等规模程序的最好方法是从结构图最底层开始，而不是从顶部开始，然后逐步上升。或者说，先运行和测试每一个基本函数，再测试由基础函数组成的整体函数，这样有助于定位错误</p>
<h3 id="计算生态"><a href="#计算生态" class="headerlink" title="计算生态"></a>计算生态</h3><p>Python官方网站提供了第三方库索引功能<a href="https://pypi.python.org/pypi" target="_blank" rel="noopener">PyPI</a></p>
<p>函数库并非都采用 Python 编写，很多采用 C 等语言编写的库可以通过简单的接口封装供 Python 程序调用。“胶水语言”。</p>
<p>Python 第三方程序包：</p>
<ul>
<li>库 library；</li>
<li>模块 module；</li>
<li>类 class；</li>
<li>程序包 package</li>
</ul>
<h3 id="实例解析–Web页面元素提取"><a href="#实例解析–Web页面元素提取" class="headerlink" title="实例解析–Web页面元素提取"></a>实例解析–Web页面元素提取</h3><p>Web页面，一般是HTML页面，是Internet组织信息的基础元素。Web页面元素提取是一类常见问题，在网络爬虫、浏览器等程序中有着不可或缺的重要作用。</p>
<p>HTML指超文本标记语言，严格来说，HTML不是一种编程语言，而是一种对信息的标记语言，对Web的内容、格式进行描述。</p>
<p>自动地从一个链接获取HTML页面是网络爬虫的功能，本实例功能可以整体分成如下4个步骤：</p>
<ul>
<li>步骤1: 读取保存在本地的html文件；</li>
<li>步骤2：解析并提取其中的图片链接；</li>
<li>步骤3：输出提取结果到屏幕；</li>
<li>步骤4：保存提取结果为文件。</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">'''</span></span><br><span class="line"><span class="string">根据上述步骤，可以写出主程序如下。</span></span><br><span class="line"><span class="string">其中设置了4个函数</span></span><br><span class="line"><span class="string">getHTMLlines()、extractImageUrls()、showResults()和saveResults()分别对应上述4个步骤。</span></span><br><span class="line"><span class="string">'''</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">getHTMLlines</span><span class="params">(htmlpath)</span>:</span></span><br><span class="line">    <span class="string">'''</span></span><br><span class="line"><span class="string">    getHTMLlines()函数读取HTML文件并内容，</span></span><br><span class="line"><span class="string">    并将结果转换为一个分行列表，</span></span><br><span class="line"><span class="string">    为了兼容不同编码，建议在open()函数中增加encoding字段，</span></span><br><span class="line"><span class="string">    设置采用UTF-8编码打开文件。</span></span><br><span class="line"><span class="string">    '''</span></span><br><span class="line">    f = open(htmlpath, <span class="string">"r"</span>, encoding=<span class="string">'utf-8'</span>)</span><br><span class="line">    ls = f.readlines()</span><br><span class="line">    f.close()</span><br><span class="line">    <span class="keyword">return</span> ls</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">extractImageUrls</span><span class="params">(htmllist)</span>:</span></span><br><span class="line">    <span class="string">'''</span></span><br><span class="line"><span class="string">    extractImageUrls()是程序的核心，用于解析文件并提取图像的URL。</span></span><br><span class="line"><span class="string">    '''</span></span><br><span class="line">    urls = []</span><br><span class="line">    <span class="keyword">for</span> line <span class="keyword">in</span> htmllist:</span><br><span class="line">        <span class="keyword">if</span> <span class="string">'img'</span> <span class="keyword">in</span> line:</span><br><span class="line">            url = line.split(<span class="string">'src='</span>)[<span class="number">-1</span>].split(<span class="string">'"'</span>)[<span class="number">1</span>]</span><br><span class="line">            <span class="keyword">if</span> <span class="string">'http'</span> <span class="keyword">in</span> url:</span><br><span class="line">                urls.append(url)</span><br><span class="line">    <span class="keyword">return</span> urls</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">showResults</span><span class="params">(urls)</span>:</span></span><br><span class="line">    <span class="string">'''</span></span><br><span class="line"><span class="string">    showResults()函数将获取的链接输出到屏幕上，</span></span><br><span class="line"><span class="string">    增加一个计数变量提供更好用户体验</span></span><br><span class="line"><span class="string">    '''</span></span><br><span class="line">    count = <span class="number">0</span></span><br><span class="line">    <span class="keyword">for</span> url <span class="keyword">in</span> urls:</span><br><span class="line">        print(<span class="string">'第&#123;:2&#125;个URL:&#123;&#125;'</span>.format(count, url))</span><br><span class="line">        count += <span class="number">1</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">saveResults</span><span class="params">(filepath, urls)</span>:</span> <span class="comment"># 保存结果到文件</span></span><br><span class="line">    f = open(filepath, <span class="string">"w"</span>)</span><br><span class="line">    <span class="keyword">for</span> url <span class="keyword">in</span> urls:</span><br><span class="line">        f.write(url+<span class="string">"\n"</span>)</span><br><span class="line">    f.close()</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">main</span><span class="params">()</span>:</span></span><br><span class="line">    <span class="string">'''</span></span><br><span class="line"><span class="string">    定义main()函数的目的是为了让代码更加清晰，</span></span><br><span class="line"><span class="string">    作为主程序，也可以不采用函数形式而直接编写。</span></span><br><span class="line"><span class="string">    main()前两行分别制定了拟获取HTML文件的路径和结果输出路径。</span></span><br><span class="line"><span class="string">    '''</span></span><br><span class="line">    inputfile  = <span class="string">'nationalgeographic.html'</span></span><br><span class="line">    outputfile = <span class="string">'nationalgeographic-urls.txt'</span></span><br><span class="line">    htmlLines = getHTMLlines(inputfile)</span><br><span class="line">    imageUrls = extractImageUrls(htmlLines)</span><br><span class="line">    showResults(imageUrls)</span><br><span class="line">    saveResults(outputfile, imageUrls)</span><br><span class="line"></span><br><span class="line">main()</span><br></pre></td></tr></table></figure>

<h2 id="Python-标准库概览"><a href="#Python-标准库概览" class="headerlink" title="Python 标准库概览"></a>Python 标准库概览</h2><p>有一部分Python计算生态随Python安装包一起发布，用户可以随时使用，被称为Python标准库。</p>
<h3 id="turtle库概述"><a href="#turtle库概述" class="headerlink" title="turtle库概述"></a>turtle库概述</h3><p>turtle 是 Python 重要的标准库之一，它能够进行基本的图形绘制。概念诞生于1969年，成功应用于 LOGO 编程语言。</p>
<p>基本框架：一个龟在坐标系中爬行，其爬行轨迹形成了绘制图形。</p>
<p>刚开始时，位于正中央，前进方向为水平右方。</p>
<p>三种引用方式：</p>
<ol>
<li><pre><code class="python"><span class="keyword">import</span> turtle
turtle.&lt;函数名&gt;()
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">2. &#96;&#96;&#96;python</span><br><span class="line">   from turtle import *</span><br><span class="line">   &lt;函数名&gt;()</span><br></pre></td></tr></table></figure></code></pre>
</li>
<li><pre><code class="python"><span class="keyword">import</span> turtle <span class="keyword">as</span> t(也可以是其他别名)
t.&lt;函数名&gt;()
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">### turtle库与基本绘图</span><br><span class="line"></span><br><span class="line">turtle库包含100多个功能函数，主要包括窗体函数、画笔状态函数、画笔运动函数等三类。</span><br><span class="line"></span><br><span class="line">#### 窗体函数：turtle.setup()</span><br><span class="line"></span><br><span class="line">&#96;turtle.setup(width, height, startx, starty)&#96;</span><br><span class="line"></span><br><span class="line">作用：设置主窗体的大小和位置。</span><br><span class="line"></span><br><span class="line">width：窗口宽度。整数：像素值；小数：窗口宽度与屏幕的比例。</span><br><span class="line"></span><br><span class="line">height：窗口高度。</span><br><span class="line"></span><br><span class="line">startx：窗口左侧与屏幕左侧的像素距离。None：水平中央。</span><br><span class="line"></span><br><span class="line">starty：窗口顶部与屏幕顶部的像素距离。None：垂直中央。</span><br><span class="line"></span><br><span class="line">#### 画笔状态函数</span><br><span class="line"></span><br><span class="line">|           函数            | 作用                                        |</span><br><span class="line">| :-----------------------: | ------------------------------------------- |</span><br><span class="line">|        &#96;pendown()&#96;        | 放下画笔                                    |</span><br><span class="line">|         &#96;penup()&#96;         | 提起画笔，与 pendown() 配对使用             |</span><br><span class="line">|        &#96;pensize()&#96;        | 设置画笔线条的粗细                          |</span><br><span class="line">|       &#96;pencolor()&#96;        | 设置颜色                                    |</span><br><span class="line">|      &#96;begin_fill()&#96;       | 填充前，调用                                |</span><br><span class="line">|       &#96;end_fill()&#96;        | 填充结束                                    |</span><br><span class="line">|        &#96;filling()&#96;        | 返回填充的状态，True 为填充，False 为未填充 |</span><br><span class="line">|         &#96;clear()&#96;         | 清空当前窗口，但不改变当前画笔位置          |</span><br><span class="line">|         &#96;reset()&#96;         | 清空并重置                                  |</span><br><span class="line">|      &#96;screensize()&#96;       | 设置画布的长与宽                            |</span><br><span class="line">|      &#96;showturtle()&#96;       | 显示画笔的 turtle 形状                      |</span><br><span class="line">|      &#96;hideturtle()&#96;       | 隐藏画笔的 turtle 形状                      |</span><br><span class="line">|       &#96;isvisible()&#96;       | 如果 turtle 可见，则返回 True               |</span><br><span class="line">| &#96;write(str, font &#x3D; None)&#96; | 输出 font 字体的 str                        |</span><br><span class="line"></span><br><span class="line">#### 画笔运动函数</span><br><span class="line"></span><br><span class="line">|        函数         | 作用                               |</span><br><span class="line">| :-----------------: | ---------------------------------- |</span><br><span class="line">|     &#96;forward()&#96;     | 前进指定距离                       |</span><br><span class="line">|    &#96;backward()&#96;     | 后退指定距离                       |</span><br><span class="line">|   &#96;right(angle)&#96;    | 向右旋转 angle 角度                |</span><br><span class="line">|    &#96;left(angle)&#96;    | 向左旋转 angle 角度                |</span><br><span class="line">|    &#96;goto(x, y)&#96;     | 移动到（x，y）处                   |</span><br><span class="line">|      &#96;setx()&#96;       | 将当前 x 轴移动到指定位置          |</span><br><span class="line">|      &#96;sety()&#96;       | 将当前 y 轴移动到指定位置          |</span><br><span class="line">| &#96;setheading(angle)&#96; | 设置当前朝向为 angle 角度          |</span><br><span class="line">|      &#96;home()&#96;       | 设置当前位置为原点，朝向东         |</span><br><span class="line">| &#96;circle(radius, e)&#96; | 绘制一个半径 r 和角度 e 的园或弧形 |</span><br><span class="line">|   &#96;dot(r, color)&#96;   | 绘制一个半径 r 和颜色的圆点        |</span><br><span class="line">|      &#96;undo()&#96;       | 撤销画笔最后一个动作               |</span><br><span class="line">|      &#96;speed()&#96;      | 设置绘制速度，参数为0~10           |</span><br><span class="line"></span><br><span class="line">### random 库概述</span><br><span class="line"></span><br><span class="line">用于产生各种分布的伪随机数序列。采用梅森旋转算法（Mersenne twiste）生成伪随机数序列，可用于除随机性要求更高的加密算法外大多数工程应用。</span><br><span class="line"></span><br><span class="line">最基本函数：&#96;random.random()&#96;，它生成 [0.0, 1.0)之间的小数</span><br><span class="line"></span><br><span class="line">### random 库与随机数应用</span><br><span class="line"></span><br><span class="line">|             函数              | 作用                                                |</span><br><span class="line">| :---------------------------: | --------------------------------------------------- |</span><br><span class="line">|        &#96;seed(a &#x3D; None)&#96;       | 初始化随机数种子，默认值为当前系统时间              |</span><br><span class="line">|           &#96;random()&#96;          | 生成 [0.0, 1.0] 之间的小数                          |</span><br><span class="line">|         &#96;randint(a, b)&#96;         | 生成一个 [a, b] 之间的整数                          |</span><br><span class="line">|        &#96;getrandbits(k)&#96;       | 生成一个 k 比特长度的随机整数                       |</span><br><span class="line">| &#96;randrange(start, stop [step])&#96; | 生成一个 [start, stop) 之间以 step 为步数的随机整数 |</span><br><span class="line">|       &#96;uniform(a, b)&#96;      | 生成一个 [a, b] 之间的随机小数                      |</span><br><span class="line">|          &#96;choice(seq)&#96;          | 从序列类型（如列表）中随机返回一个元素              |</span><br><span class="line">|         &#96;shuffle(seq)&#96;        | 将序列类型中元素随机排列，返回序列                  |</span><br><span class="line">|        &#96;sample(pop, k)&#96;       | 从 pop 类型中随机选取 k 个元素，以列表类型返回      |</span><br><span class="line"></span><br><span class="line">### time 库概述</span><br><span class="line"></span><br><span class="line">Python 提供的处理时间标准库。提供系统级精确计时器的计时功能，可以用来分析程序性能，也可以让程序暂停运行时间。</span><br><span class="line"></span><br><span class="line">3方面主要功能：</span><br><span class="line"></span><br><span class="line">1. 时间处理：&#96;time.time()&#96;、&#96;time.gmtime()&#96;、&#96;time.localtime()&#96;、&#96;time.ctime()&#96;</span><br><span class="line">2. 时间格式化：&#96;time.mktime()&#96;、&#96;time.strftime()&#96;、&#96;time.strptime()&#96;</span><br><span class="line">3. 计时：&#96;time.sleep()&#96;、&#96;time.monotonic()&#96;、&#96;time.perf_counter()&#96;</span><br><span class="line"></span><br><span class="line">|         函数          | 作用                                                         |</span><br><span class="line">| :-------------------: | ------------------------------------------------------------ |</span><br><span class="line">|     &#96;time.time()&#96;     | 获取当前的时间戳                                             |</span><br><span class="line">|    &#96;time.gmtime()&#96;    | 获取当前时间戳对应的 struct_time 对象                        |</span><br><span class="line">|  &#96;time.localtime()&#96;   | 获取当前时间戳对应的本地时间的 struct_time 对象              |</span><br><span class="line">|    &#96;time.ctime()&#96;     | 获取当前时间戳对应的易读字符串表示，内部会调用 time.localtime() |</span><br><span class="line">|    &#96;time.mktime()&#96;    | 将 srtuct_time 转换为时间戳                                  |</span><br><span class="line">|   &#96;time.strftime()&#96;   | 时间格式化最有效的方法，几乎可以以任何通用格式输出时间       |</span><br><span class="line">|   &#96;time.strptime()&#96;   | 提取字符串中的时间来生成 struct_time                         |</span><br><span class="line">| &#96;time.perf_counter()&#96; | 返回计时器的精准时间（系统的运行时间），包含整个系统的睡眠时间。由于返回值的基准点是未定义的，所以，只有连续调用的结果之间的差才是有效的。&lt;br &#x2F;&gt;调用一次 &#96;perf_counter()&#96;，从计算机系统里随机选一个时间点A，计算其距离当前时间点B1有多少秒。当第二次调用该函数时，默认从第一次调用的时间点A算起，距离当前时间点B2有多少秒。两个函数取差，即实现从时间点B1到B2的计时功能。 |</span><br><span class="line"></span><br><span class="line">&#96;struct_time&#96; 元素</span><br><span class="line"></span><br><span class="line">| 下标 |   属性   | 值                           |</span><br><span class="line">| :--: | :------: | ---------------------------- |</span><br><span class="line">|  0   | tm_year  | 年份，整数                   |</span><br><span class="line">|  1   |  tm_mon  | 月份 [1, 12]                 |</span><br><span class="line">|  2   | tm_mday  | 日期 [1, 31]                 |</span><br><span class="line">|  3   | tm_hour  | 小时 [0, 23]                 |</span><br><span class="line">|  4   |  tm_min  | 分钟 [0, 59]                 |</span><br><span class="line">|  5   |  tm_sec  | 秒 [0, 61]                   |</span><br><span class="line">|  6   | tm_wday  | 星期 [0, 6] （0 表示星期一） |</span><br><span class="line">|  7   | tm_yday  | 该年第几天 [1, 366]          |</span><br><span class="line">|  8   | tm_isdst | 是否夏令时，0否，1是，-1未知 |</span><br><span class="line"></span><br><span class="line">&#96;time.strftime()&#96;:</span><br><span class="line"></span><br><span class="line">&#96;time.strftime(&#39;&lt;参数&gt;&#39;, time)&#96;</span><br><span class="line"></span><br><span class="line">| 参数符号 |  日期&#x2F;时间  |       值范围       |</span><br><span class="line">| :------: | :---------: | :----------------: |</span><br><span class="line">|    %Y    |    年份     |    0001 - 9999     |</span><br><span class="line">|    %m    |    月份     |      01 - 12       |</span><br><span class="line">|    %B    |    月名     | January - December |</span><br><span class="line">|    %b    |  月名缩写   |    Jan. - Dec.     |</span><br><span class="line">|    %d    |    日期     |      01 - 31       |</span><br><span class="line">|    %A    |    星期     |  Monday - Sunday   |</span><br><span class="line">|    %a    |  星期缩写   |    Mon. - Sun.     |</span><br><span class="line">|    %H    | 小时（24h） |      00 - 23       |</span><br><span class="line">|    %I    |     12h     |      01 - 12       |</span><br><span class="line">|    %p    |   上&#x2F;下午   |       AM, PM       |</span><br><span class="line">|    %M    |    分钟     |       00 -59       |</span><br><span class="line">|    %S    |     秒      |      00 - 59       |</span><br><span class="line"></span><br><span class="line">### time 库与程序计时</span><br><span class="line"></span><br><span class="line">三要素：</span><br><span class="line"></span><br><span class="line">+ 程序开始&#x2F;结束时间</span><br><span class="line">+ 程序运行时间</span><br><span class="line">+ 程序各核心模块运行时间</span><br><span class="line"></span><br><span class="line">&#96;time.sleep(t)&#96;：推迟 t 秒执行</span><br><span class="line"></span><br><span class="line">&#96;time.perf_counter()&#96;：计时器，每次调用记录当前执行时间</span><br><span class="line"></span><br><span class="line">### 实例解析--雪景艺术绘图</span><br><span class="line"></span><br><span class="line">turtle图形艺术，指利用turtle库画笔创造性绘制绚丽多彩艺术图形的过程</span><br><span class="line"></span><br><span class="line">turtle图形艺术效果中隐含着很多随机元素，如随机颜色、尺寸、位置和数量等。在图形艺术绘制中需要引入随机函数库random。常用randint()函数，生成指定范围内的随机数</span><br><span class="line"></span><br><span class="line">绘制分为三个步骤:</span><br><span class="line"></span><br><span class="line">1. 构建图的背景</span><br><span class="line">2. 绘制雪花效果</span><br><span class="line">3. 绘制雪地效果</span><br><span class="line"></span><br><span class="line">&#96;&#96;&#96;python</span><br><span class="line">from turtle import *</span><br><span class="line">from random import *</span><br><span class="line"># 第二步，绘制雪花效果。</span><br><span class="line">def drawSnow():</span><br><span class="line">    hideturtle()</span><br><span class="line">    pensize(2)</span><br><span class="line">    for i in range(100):</span><br><span class="line">        r, g, b &#x3D; random(), random(), random()</span><br><span class="line">        pencolor(r,g,b)</span><br><span class="line">        penup()</span><br><span class="line">        setx(randint(-350,350))</span><br><span class="line">        sety(randint(1,270))</span><br><span class="line">        pendown()</span><br><span class="line">        dens &#x3D; randint(8,12)</span><br><span class="line">        snowsize &#x3D; randint(10,14)</span><br><span class="line">        for j in range(dens):</span><br><span class="line">            forward(snowsize)</span><br><span class="line">            backward(snowsize)</span><br><span class="line">            right(360&#x2F;dens)</span><br><span class="line"># 第三步，绘制雪地效果。</span><br><span class="line">def drawGround():</span><br><span class="line">    hideturtle()</span><br><span class="line">    for i in range(400):</span><br><span class="line">        pensize(randint(5,10))</span><br><span class="line">        x &#x3D; randint(-400,350)</span><br><span class="line">        y &#x3D; randint(-280,-1)</span><br><span class="line">        r, g, b &#x3D; -y&#x2F;280, -y&#x2F;280, -y&#x2F;280</span><br><span class="line">        pencolor((r,g,b))</span><br><span class="line">        penup()</span><br><span class="line">        goto(x,y)</span><br><span class="line">        pendown()</span><br><span class="line">        forward(randint(40,100))</span><br><span class="line"># 第一步，构建图的背景</span><br><span class="line">setup(800,600,200,200)</span><br><span class="line">tracer(False)</span><br><span class="line">bgcolor(&quot;black&quot;)</span><br><span class="line">drawSnow()</span><br><span class="line">drawGround()</span><br><span class="line">done()</span><br></pre></td></tr></table></figure>
</code></pre>
</li>
</ol>
<h2 id="Python-第三方库概览"><a href="#Python-第三方库概览" class="headerlink" title="Python 第三方库概览"></a>Python 第三方库概览</h2><h3 id="获取和安装"><a href="#获取和安装" class="headerlink" title="获取和安装"></a>获取和安装</h3><h4 id="pip-工具"><a href="#pip-工具" class="headerlink" title="pip 工具"></a>pip 工具</h4><p>是 Python 官方提供并维护的在线第三方库安装工具。</p>
<p><code>pip install &lt;库名&gt;</code></p>
<h4 id="自定义安装"><a href="#自定义安装" class="headerlink" title="自定义安装"></a>自定义安装</h4><p>一般适用于在 pip 中尚无登记或安装失败的第三方库</p>
<p>美国加州大学尔湾分校提供了一个页面，帮助Python用户获得Windows可直<br>接安装的第三方库文件，<a href="https://www.lfd.uci.edu/~gohlke/pythonlibs/" target="_blank" rel="noopener">链接地址</a></p>
<p>这里以scipy为例说明，首先在上述页面中找到scipy库对应的内容。选择其中的.whl文件下载，这里选择适用于Python 3.5版本解释器和32位系统的对应文件：scipy-0 . 1 7 . 1 - c p 3 5 - c p 3 5 m - w i n 3 2 . w h l ， 下载该文件到<br>D:\pycodes目录。</p>
<p>然后，采用pip命令安装该文件。</p>
<p><code>pip install D:\pycodes\scipy-0.17.1-cp35-cp35m-win32.whl</code></p>
<h4 id="pip-工具使用"><a href="#pip-工具使用" class="headerlink" title="pip 工具使用"></a>pip 工具使用</h4><figure class="highlight powershell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">pip install &lt;库名&gt; <span class="comment">#安装</span></span><br><span class="line">pip uninstall &lt;库名&gt; <span class="comment">#卸载</span></span><br><span class="line">pip list <span class="comment">#列出当前系统以安装的第三方库</span></span><br><span class="line">pip show &lt;库名&gt; <span class="comment">#列出某个以安装库的详细信息</span></span><br><span class="line">pip download &lt;库名&gt; <span class="comment">#下载第三方库的安装包，但不安装</span></span><br><span class="line">pip search &lt;关键字&gt; <span class="comment">#联网搜索库名或摘要中的关键字</span></span><br><span class="line">pip <span class="literal">-h</span>  <span class="comment">#列出pip常用的子命令</span></span><br></pre></td></tr></table></figure>

<h3 id="PyInstaller-库"><a href="#PyInstaller-库" class="headerlink" title="PyInstaller 库"></a>PyInstaller 库</h3><p>将 Python 源文件（.py）打包，变成直接可运行的可执行文件。</p>
<p>使用PyInstaller库对Python源文件打包十分简单，使用方法如下：</p>
<p><code>PyInstaller &lt;程序文件名&gt;</code></p>
<p>生成 dist 和 build 文件夹。build 是存储临时文件的目录。最终的打包程序在dist内部与源文件同名的目录中。</p>
<p>注意问题：</p>
<ul>
<li>文件路径中不能出现空格和英文句号（.）</li>
<li>源文件必须是 UTF-8 编码</li>
</ul>
<table>
<thead>
<tr>
<th align="center">常用参数</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td align="center">-h, –help</td>
<td>查看帮助</td>
</tr>
<tr>
<td align="center">–clean</td>
<td>清理打包过程中的临时文件</td>
</tr>
<tr>
<td align="center">-D, –onedir</td>
<td>默认值，生成 dist 目录</td>
</tr>
<tr>
<td align="center">-F, –onefile</td>
<td>在 dist 文件夹中只生成独立的打包文件</td>
</tr>
<tr>
<td align="center">-i, &lt;图标.ico&gt;</td>
<td>指定打包程序使用的图标文件</td>
</tr>
</tbody></table>
<h3 id="jieba-库"><a href="#jieba-库" class="headerlink" title="jieba 库"></a>jieba 库</h3><p>重要的第三方中文分词函数库</p>
<p>原理：是利用一个中文词库，将待分词的内容与分词词库进行比对，通过图结构和动态规划方法找到最大概率的词组。除了分词，jieba还提供增加自定义中文单词的功能。</p>
<p>三模式：</p>
<ol>
<li>精确模式：最精确地切开，适合文本分析；</li>
<li>全模式：把句子中所有可以成词的词语都扫描出来，但是不能解歧义；</li>
<li>搜索引擎模式：在精确模式的基础上，对长词再次切分，提高召回率，适合用于搜索引擎分词</li>
</ol>
<table>
<thead>
<tr>
<th align="center">函数</th>
<th>作用</th>
</tr>
</thead>
<tbody><tr>
<td align="center"><code>lcut(s)</code></td>
<td>精确模式，返回列表</td>
</tr>
<tr>
<td align="center"><code>lcut(s, cut_all = True)</code></td>
<td>全模式</td>
</tr>
<tr>
<td align="center"><code>lcut_for_search(s)</code></td>
<td>搜索模式</td>
</tr>
<tr>
<td align="center"><code>add_word(w)</code></td>
<td>向词典中添加新词 w</td>
</tr>
</tbody></table>
<h3 id="wordcloud-库"><a href="#wordcloud-库" class="headerlink" title="wordcloud 库"></a>wordcloud 库</h3><p>“关键词云层”、“关键词渲染”</p>
<table>
<thead>
<tr>
<th align="center">常用参数</th>
<th>功能</th>
</tr>
</thead>
<tbody><tr>
<td align="center"><code>font_path</code></td>
<td>指定字体文件的完整路径，默认 None</td>
</tr>
<tr>
<td align="center"><code>width</code></td>
<td>生成图片宽度，默认400像素</td>
</tr>
<tr>
<td align="center"><code>height</code></td>
<td>生成图片高度，默认200像素</td>
</tr>
<tr>
<td align="center"><code>mask</code></td>
<td>词云形状，默认 None，方形图</td>
</tr>
<tr>
<td align="center"><code>min_font_size</code></td>
<td>词云中最小的字体字号，默认4号</td>
</tr>
<tr>
<td align="center"><code>font_step</code></td>
<td>字号步进间隔，默认1</td>
</tr>
<tr>
<td align="center"><code>stopwords</code></td>
<td>被排除词列表，排除词不再词云中显示</td>
</tr>
<tr>
<td align="center"><code>background_color</code></td>
<td>背景颜色，默认黑色</td>
</tr>
<tr>
<td align="center"><code>max_words</code></td>
<td>词云中最大词数，默认200</td>
</tr>
<tr>
<td align="center"><code>max_font_size</code></td>
<td>词云中最大的字体字号，默认 None，根据高度自动调整</td>
</tr>
</tbody></table>
<table>
<thead>
<tr>
<th align="center">常用方法</th>
<th>功能</th>
</tr>
</thead>
<tbody><tr>
<td align="center"><code>generate(text)</code></td>
<td>生成词云</td>
</tr>
<tr>
<td align="center"><code>tofile(filename)</code></td>
<td>保存</td>
</tr>
</tbody></table>
<p>图像词云：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> scipy.misc <span class="keyword">import</span> imread</span><br><span class="line">mask = imread(<span class="string">'***.png'</span>)</span><br></pre></td></tr></table></figure>

<h3 id="实例解析–《红楼梦》人物出场词云"><a href="#实例解析–《红楼梦》人物出场词云" class="headerlink" title="实例解析–《红楼梦》人物出场词云"></a>实例解析–《红楼梦》人物出场词云</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 先输出排序前15的单词</span></span><br><span class="line"><span class="keyword">import</span> jieba</span><br><span class="line">f = open(<span class="string">"红楼梦.txt"</span>, <span class="string">"r"</span>, encoding=<span class="string">"utf-8"</span>)</span><br><span class="line">txt = f.read()</span><br><span class="line">f.close()</span><br><span class="line">words  = jieba.lcut(txt)</span><br><span class="line">counts = &#123;&#125;</span><br><span class="line"><span class="keyword">for</span> word <span class="keyword">in</span> words:</span><br><span class="line">    <span class="keyword">if</span> len(word) == <span class="number">1</span>:  <span class="comment">#排除单个字符的分词结果</span></span><br><span class="line">        <span class="keyword">continue</span></span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        counts[word] = counts.get(word,<span class="number">0</span>) + <span class="number">1</span></span><br><span class="line">items = list(counts.items())</span><br><span class="line">items.sort(key=<span class="keyword">lambda</span> x:x[<span class="number">1</span>], reverse=<span class="literal">True</span>)</span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">15</span>):</span><br><span class="line">    word, count = items[i]</span><br><span class="line">    <span class="keyword">print</span> (<span class="string">"&#123;0:&lt;10&#125;&#123;1:&gt;5&#125;"</span>.format(word, count))</span><br></pre></td></tr></table></figure>

<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 需要排除一些人名无关词汇，如“什么”、“一个”等</span></span><br><span class="line"><span class="keyword">import</span> jieba</span><br><span class="line">excludes = &#123;<span class="string">"什么"</span>,<span class="string">"一个"</span>,<span class="string">"我们"</span>,<span class="string">"那里"</span>,<span class="string">"你们"</span>,<span class="string">"如今"</span>, \</span><br><span class="line">            <span class="string">"说道"</span>,<span class="string">"知道"</span>,<span class="string">"老太太"</span>,<span class="string">"起来"</span>,<span class="string">"姑娘"</span>,<span class="string">"这里"</span>, \</span><br><span class="line">            <span class="string">"出来"</span>,<span class="string">"他们"</span>,<span class="string">"众人"</span>,<span class="string">"自己"</span>,<span class="string">"一面"</span>,<span class="string">"太太"</span>, \</span><br><span class="line">            <span class="string">"只见"</span>,<span class="string">"怎么"</span>,<span class="string">"奶奶"</span>,<span class="string">"两个"</span>,<span class="string">"没有"</span>,<span class="string">"不是"</span>, \</span><br><span class="line">            <span class="string">"不知"</span>,<span class="string">"这个"</span>,<span class="string">"听见"</span>&#125;</span><br><span class="line">f = open(<span class="string">"红楼梦.txt"</span>, <span class="string">"r"</span>, encoding=<span class="string">"utf-8"</span>)</span><br><span class="line">txt = f.read()</span><br><span class="line">f.close()</span><br><span class="line">words  = jieba.lcut(txt)</span><br><span class="line">counts = &#123;&#125;</span><br><span class="line"><span class="keyword">for</span> word <span class="keyword">in</span> words:</span><br><span class="line">    <span class="keyword">if</span> len(word) == <span class="number">1</span>:  <span class="comment">#排除单个字符的分词结果</span></span><br><span class="line">        <span class="keyword">continue</span></span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        counts[word] = counts.get(word,<span class="number">0</span>) + <span class="number">1</span></span><br><span class="line"><span class="keyword">for</span> word <span class="keyword">in</span> excludes:</span><br><span class="line">    <span class="keyword">del</span>(counts[word])</span><br><span class="line">items = list(counts.items())</span><br><span class="line">items.sort(key=<span class="keyword">lambda</span> x:x[<span class="number">1</span>], reverse=<span class="literal">True</span>)</span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">5</span>):</span><br><span class="line">    word, count = items[i]</span><br><span class="line">    <span class="keyword">print</span> (<span class="string">"&#123;0:&lt;10&#125;&#123;1:&gt;5&#125;"</span>.format(word, count))</span><br></pre></td></tr></table></figure>

<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 结合已经将结果的词云效果，利用wordcloud库，将人物出场统计以词云的方式展现出来</span></span><br><span class="line"><span class="keyword">import</span> jieba</span><br><span class="line"><span class="keyword">from</span> wordcloud <span class="keyword">import</span> WordCloud</span><br><span class="line"></span><br><span class="line">excludes = &#123;<span class="string">"什么"</span>,<span class="string">"一个"</span>,<span class="string">"我们"</span>,<span class="string">"那里"</span>,<span class="string">"你们"</span>,<span class="string">"如今"</span>, \</span><br><span class="line">            <span class="string">"说道"</span>,<span class="string">"知道"</span>,<span class="string">"老太太"</span>,<span class="string">"起来"</span>,<span class="string">"姑娘"</span>,<span class="string">"这里"</span>, \</span><br><span class="line">            <span class="string">"出来"</span>,<span class="string">"他们"</span>,<span class="string">"众人"</span>,<span class="string">"自己"</span>,<span class="string">"一面"</span>,<span class="string">"太太"</span>, \</span><br><span class="line">            <span class="string">"只见"</span>,<span class="string">"怎么"</span>,<span class="string">"奶奶"</span>,<span class="string">"两个"</span>,<span class="string">"没有"</span>,<span class="string">"不是"</span>, \</span><br><span class="line">            <span class="string">"不知"</span>,<span class="string">"这个"</span>,<span class="string">"听见"</span>&#125;</span><br><span class="line">f = open(<span class="string">"红楼梦.txt"</span>, <span class="string">"r"</span>, encoding=<span class="string">"utf-8"</span>)</span><br><span class="line">txt = f.read()</span><br><span class="line">f.close()</span><br><span class="line">words  = jieba.lcut(txt)</span><br><span class="line">newtxt = <span class="string">' '</span>.join(words)</span><br><span class="line">wordcloud = WordCloud(background_color=<span class="string">"white"</span>, \</span><br><span class="line">                          width=<span class="number">800</span>, \</span><br><span class="line">                          height=<span class="number">600</span>, \</span><br><span class="line">                          font_path=<span class="string">"msyh.ttc"</span>, \</span><br><span class="line">                          max_words=<span class="number">200</span>, \</span><br><span class="line">                          max_font_size=<span class="number">80</span>, \</span><br><span class="line">                          stopwords = excludes, \</span><br><span class="line">                          ).generate(newtxt)</span><br><span class="line">wordcloud.to_file(<span class="string">'红楼梦基本词云.png'</span>)</span><br></pre></td></tr></table></figure>

<h2 id="Python-第三方库纵览"><a href="#Python-第三方库纵览" class="headerlink" title="Python 第三方库纵览"></a>Python 第三方库纵览</h2><h3 id="网络爬虫方向"><a href="#网络爬虫方向" class="headerlink" title="网络爬虫方向"></a>网络爬虫方向</h3><p>自动进行 HTTP 访问并捕获 HTML 页面的程序。</p>
<h4 id="requests"><a href="#requests" class="headerlink" title="requests"></a>requests</h4><p>简洁且简单</p>
<table>
<thead>
<tr>
<th align="center">函数</th>
<th>功能</th>
</tr>
</thead>
<tbody><tr>
<td align="center"><code>request()</code></td>
<td>构建一个请求</td>
</tr>
<tr>
<td align="center"><code>get()</code></td>
<td>获取 HTML 网页的主要方法</td>
</tr>
<tr>
<td align="center"><code>head()</code></td>
<td>获取 HTML 网页头信息</td>
</tr>
<tr>
<td align="center"><code>post()</code></td>
<td>提交 POST 请求</td>
</tr>
<tr>
<td align="center"><code>patch()</code></td>
<td>提交局部修改请求</td>
</tr>
<tr>
<td align="center"><code>delete()</code></td>
<td>提交删除请求</td>
</tr>
<tr>
<td align="center"><code>put()</code></td>
<td>提交 PUT 请求</td>
</tr>
</tbody></table>
<h4 id="scrapy"><a href="#scrapy" class="headerlink" title="scrapy"></a>scrapy</h4><p>快速的、高层次的 web 获取框架</p>
<h3 id="数据分析方向"><a href="#数据分析方向" class="headerlink" title="数据分析方向"></a>数据分析方向</h3><h4 id="numpy"><a href="#numpy" class="headerlink" title="numpy"></a>numpy</h4><p>开源数值计算扩展第三方库，用于处理数据类型相同的多维数据（ndarray），“数组”。</p>
<h4 id="scipy"><a href="#scipy" class="headerlink" title="scipy"></a>scipy</h4><p>在 numpy 库的基础沈阳增加了众多的科学、数学以及工程计算中常用的库函数。包括统计、优化、整合、线性代数、傅里叶变换、信号分析、图像处理、常微分方程求解等众多模块。</p>
<h4 id="pandas"><a href="#pandas" class="headerlink" title="pandas"></a>pandas</h4><p>基于 numpy 扩展。为解决数据分析任务。</p>
<h3 id="文本处理方向"><a href="#文本处理方向" class="headerlink" title="文本处理方向"></a>文本处理方向</h3><h4 id="pdfminer"><a href="#pdfminer" class="headerlink" title="pdfminer"></a>pdfminer</h4><p>一个可以从 PDF 文档中提取各类信息的第三方库。</p>
<h4 id="openpyxl"><a href="#openpyxl" class="headerlink" title="openpyxl"></a>openpyxl</h4><p>一个处理 Excel 文档的 Python 第三方库。</p>
<h4 id="python-docx"><a href="#python-docx" class="headerlink" title="python_docx"></a>python_docx</h4><p>一个处理 Word 文档的第三方库。</p>
<h4 id="beautifulsoup4"><a href="#beautifulsoup4" class="headerlink" title="beautifulsoup4"></a>beautifulsoup4</h4><p>用于解析和处理 HTML 和 XML。</p>
<h3 id="数据可视化方向"><a href="#数据可视化方向" class="headerlink" title="数据可视化方向"></a>数据可视化方向</h3><p>指根据数据特点将其展示为易于理解的图形的过程。</p>
<h4 id="matplotlib"><a href="#matplotlib" class="headerlink" title="matplotlib"></a>matplotlib</h4><p>主要进行二维图标数据展示，广泛用于科学计算的数据可视化。</p>
<h4 id="TVTK"><a href="#TVTK" class="headerlink" title="TVTK"></a>TVTK</h4><p>专业可编程的三维可视化工具。</p>
<h4 id="mayavi"><a href="#mayavi" class="headerlink" title="mayavi"></a>mayavi</h4><p>基于 VTK 开发，完全用 Python 编写。</p>
<h3 id="用户图形界面方向"><a href="#用户图形界面方向" class="headerlink" title="用户图形界面方向"></a>用户图形界面方向</h3><h4 id="PyQt5"><a href="#PyQt5" class="headerlink" title="PyQt5"></a>PyQt5</h4><p>最成熟的商业级 GUI 第三方库。</p>
<h4 id="wxPython"><a href="#wxPython" class="headerlink" title="wxPython"></a>wxPython</h4><p>wxPython是Python语言的一套优秀的GUI图形库，它是跨平台GUI库wxWidgets的Python封装，可以使Python程序员能够轻松地创建健壮可靠、功能强大的图形用户界面的程序。</p>
<h4 id="PyGTK"><a href="#PyGTK" class="headerlink" title="PyGTK"></a>PyGTK</h4><h3 id="机器学习方向"><a href="#机器学习方向" class="headerlink" title="机器学习方向"></a>机器学习方向</h3><h4 id="scikit-learn"><a href="#scikit-learn" class="headerlink" title="scikit-learn"></a>scikit-learn</h4><p>一个简单且高效的数据挖掘和数据分析工具。</p>
<h4 id="TensorFlow"><a href="#TensorFlow" class="headerlink" title="TensorFlow"></a>TensorFlow</h4><p>Google 基于 DistBelief 进行研发的第二代人工智能学习系统。</p>
<h4 id="Theano"><a href="#Theano" class="headerlink" title="Theano"></a>Theano</h4><p>为执行深度学习中大规模神经网络算法而设计，擅长处理多维数组。</p>
<h3 id="Web-开发方向"><a href="#Web-开发方向" class="headerlink" title="Web 开发方向"></a>Web 开发方向</h3><h4 id="Django"><a href="#Django" class="headerlink" title="Django"></a>Django</h4><p>最流行的开源 Web 应用框架。</p>
<h4 id="Pyramid"><a href="#Pyramid" class="headerlink" title="Pyramid"></a>Pyramid</h4><p>相对小巧、快速、灵活的开源 Python Web 框架。</p>
<h4 id="Flask"><a href="#Flask" class="headerlink" title="Flask"></a>Flask</h4><p>轻量级 Web 应用框架。</p>
<h3 id="8-游戏开发方向"><a href="#8-游戏开发方向" class="headerlink" title="8.游戏开发方向"></a>8.游戏开发方向</h3><h4 id="Pygame"><a href="#Pygame" class="headerlink" title="Pygame"></a>Pygame</h4><p>在 SDL 库基础上进行封装的、面向游戏开发入门的 Python 第三方库。</p>
<h4 id="Panda3D"><a href="#Panda3D" class="headerlink" title="Panda3D"></a>Panda3D</h4><p>一个开源、跨平台的3D渲染和游戏开发库。</p>
<h4 id="cocos2d"><a href="#cocos2d" class="headerlink" title="cocos2d"></a>cocos2d</h4><p>一个构建2D游戏和图形界面交互式应用的框架。</p>
<h3 id="更多"><a href="#更多" class="headerlink" title="更多"></a>更多</h3><h4 id="PIL"><a href="#PIL" class="headerlink" title="PIL"></a>PIL</h4><p>在图像处理方面的重要第三方库。</p>
<ul>
<li>图像归档：<ol>
<li>对图像进行批处理；</li>
<li>生成图像预览；</li>
<li>图像格式转换等。</li>
</ol>
</li>
<li>图像处理：<ol>
<li>基本处理；</li>
<li>像素处理；</li>
<li>颜色处理等。</li>
</ol>
</li>
</ul>
<h4 id="SymPY"><a href="#SymPY" class="headerlink" title="SymPY"></a>SymPY</h4><p>一个支持符号计算的第三方库。一个全功能的计算机代数系统。</p>
<h4 id="NLTK"><a href="#NLTK" class="headerlink" title="NLTK"></a>NLTK</h4><p>自然语言处理第三方库。</p>
<p>语料处理、文本统计、内容理解、情感分析等多种应用。</p>
<h4 id="WeRoBot"><a href="#WeRoBot" class="headerlink" title="WeRoBot"></a>WeRoBot</h4><p>一个微信公众号开发框架，也成为微信机器人框架。</p>
<h4 id="MyQR"><a href="#MyQR" class="headerlink" title="MyQR"></a>MyQR</h4><p>一个能够产生基本二维码、艺术二维码和动态二维码的第三方库。</p>
<h2 id="附录"><a href="#附录" class="headerlink" title="附录"></a>附录</h2><h3 id="常用-Unicode-编码表"><a href="#常用-Unicode-编码表" class="headerlink" title="常用 Unicode 编码表"></a>常用 Unicode 编码表</h3><table>
<thead>
<tr>
<th align="center">名称</th>
<th align="center">范围</th>
</tr>
</thead>
<tbody><tr>
<td align="center">基础汉字</td>
<td align="center">[0x4e00, 0x9fa5]</td>
</tr>
<tr>
<td align="center">数字</td>
<td align="center">[0x0030, 0x0039]</td>
</tr>
<tr>
<td align="center">小写字母</td>
<td align="center">[0x0061, 0x007a]</td>
</tr>
<tr>
<td align="center">大写字母</td>
<td align="center">[0x0041, 0x005a]</td>
</tr>
<tr>
<td align="center">箭头</td>
<td align="center">[0x2190, 0x21ff]</td>
</tr>
<tr>
<td align="center">数字运算符</td>
<td align="center">[0x2200, 0x22ff]</td>
</tr>
<tr>
<td align="center">封闭式字母数字</td>
<td align="center">[0x2460, 0x24ff]</td>
</tr>
<tr>
<td align="center">制表符</td>
<td align="center">[0x2500, 0x257f]</td>
</tr>
<tr>
<td align="center">方块元素</td>
<td align="center">[0x2580, 0x259f]</td>
</tr>
<tr>
<td align="center">几何图形</td>
<td align="center">[0x25A0, 0x25ff]</td>
</tr>
<tr>
<td align="center">一般标点符号</td>
<td align="center">[0x2000, 0x206f]</td>
</tr>
<tr>
<td align="center">韩文</td>
<td align="center">[0xAC00, 0xD7A3]</td>
</tr>
<tr>
<td align="center">货币</td>
<td align="center">[0x20a0, 0x20cf]</td>
</tr>
<tr>
<td align="center">泰文</td>
<td align="center">[0x0e00, 0x07f]</td>
</tr>
<tr>
<td align="center">中日韩符号</td>
<td align="center">[0x3000, 0x303f]</td>
</tr>
<tr>
<td align="center">中日韩括号数字</td>
<td align="center">[0x3200, 0x32ff]</td>
</tr>
</tbody></table>
<h3 id="转义字符"><a href="#转义字符" class="headerlink" title="转义字符"></a>转义字符</h3><table>
<thead>
<tr>
<th align="center">符号</th>
<th>作用</th>
</tr>
</thead>
<tbody><tr>
<td align="center"><code>\</code></td>
<td>（在行尾时）续行符</td>
</tr>
<tr>
<td align="center"><code>\\</code></td>
<td>反斜杠符号</td>
</tr>
<tr>
<td align="center"><code>&#39;</code></td>
<td>单引号</td>
</tr>
<tr>
<td align="center"><code>&quot;</code></td>
<td>双引号</td>
</tr>
<tr>
<td align="center"><code>\a</code></td>
<td>响铃</td>
</tr>
<tr>
<td align="center"><code>\b</code></td>
<td>退格（Backspace）</td>
</tr>
<tr>
<td align="center"><code>\e</code></td>
<td>转义</td>
</tr>
<tr>
<td align="center"><code>\000</code></td>
<td>空</td>
</tr>
<tr>
<td align="center"><code>\n</code></td>
<td>换行</td>
</tr>
<tr>
<td align="center"><code>\v</code></td>
<td>纵向制表符</td>
</tr>
<tr>
<td align="center"><code>\t</code></td>
<td>横向制表符</td>
</tr>
<tr>
<td align="center"><code>\r</code></td>
<td>回车</td>
</tr>
<tr>
<td align="center"><code>\f</code></td>
<td>换页</td>
</tr>
</tbody></table>
<h3 id="基本的Python内置函数"><a href="#基本的Python内置函数" class="headerlink" title="基本的Python内置函数"></a>基本的Python内置函数</h3><p>Python解释器提供了68个内置函数</p>
<table>
<thead>
<tr>
<th>函数名称</th>
<th>函数说明</th>
</tr>
</thead>
<tbody><tr>
<td><code>abs(x)</code></td>
<td>x的绝对值，如果x是复数，返回复数的模</td>
</tr>
<tr>
<td><code>all(x)</code></td>
<td>组合类型变量x中所有元素都为真时返回True，否则返回False；若x为空，返回True</td>
</tr>
<tr>
<td><code>any(x)</code></td>
<td>组合类型变量x中任一元素都为真时返回True，否则返回False；若x为空，返回False</td>
</tr>
<tr>
<td><code>bin(x)</code></td>
<td>将整数x转换为等值的二进制字符串<br /><code>bin(1010)</code>的结果是’0b1111110010’</td>
</tr>
<tr>
<td><code>bool(x)</code></td>
<td>将x转换为Boolean类型，即True或False<br /><code>bool(&#39;&#39;)</code>的结果是False</td>
</tr>
<tr>
<td><code>chr(i)</code></td>
<td>返回Unicode为i的字符<br/><code>chr(9996)</code>的结果是’✌ ‘</td>
</tr>
<tr>
<td><code>complex(r,i)</code></td>
<td>创建一个复数 r + i*1j，其中i可以省略<br/><code>complex(10,10)</code>的结果是10+10j</td>
</tr>
<tr>
<td><code>dict()</code></td>
<td>创建字典类型<br/><code>dict()</code>的结果是一个空字典{}</td>
</tr>
<tr>
<td><code>divmod(a,b)</code></td>
<td>返回a和b的商及余数<br/><code>divmod(10,3)</code>结果是一个(3,1)</td>
</tr>
<tr>
<td><code>eval(s)</code></td>
<td>计算字符串s作为Python表达式的值<br/><code>eval(&#39;1+99&#39;)</code>的结果是100</td>
</tr>
<tr>
<td><code>exec(s)</code></td>
<td>计算字符串s作为Python语句的值<br /><code>exec(&#39;a = 1+999&#39;)</code>运行后，变量a的值为1000</td>
</tr>
<tr>
<td><code>float(x)</code></td>
<td>将x转换成浮点数<br/><code>float(1010)</code>的结果是1010.0</td>
</tr>
<tr>
<td><code>hex(x)</code></td>
<td>将整数转换为16进制字符串<br/><code>hex(1010)</code>的结果是’0x3f2</td>
</tr>
<tr>
<td><code>input(s)</code></td>
<td>获取用户输入，其中s是字符串，作为提示信息可选</td>
</tr>
<tr>
<td><code>int(x)</code></td>
<td>将x转换成整数<br/>int(9.9)的结果是9</td>
</tr>
<tr>
<td><code>list(x)</code></td>
<td>创建或将变量x转换成一个列表类型<br/><code>list({10,9,8})</code>的结果是<code>[8,9,10]</code></td>
</tr>
<tr>
<td><code>max(a1,a2,…)</code></td>
<td>返回参数的最大值</td>
</tr>
<tr>
<td><code>min(a1,a2,…)</code></td>
<td>返回参数的最小值</td>
</tr>
<tr>
<td><code>oct(x)</code></td>
<td>将整数x转换成等值的八进制字符串形式<br /><code>oct(1010)</code>的结果是’0o1762’</td>
</tr>
<tr>
<td><code>open(fname, m)</code></td>
<td>打开文件，包括文本方式和二进制方式等<br/>其中，m部分可以省略，默认是以文本可读形式打开</td>
</tr>
<tr>
<td><code>ord(c)</code></td>
<td>返回一个字符的Unicode编码值<br/><code>ord(&#39;字&#39;)</code>的结果是23383</td>
</tr>
<tr>
<td><code>pow(x,y</code></td>
<td>返回x的y次幂<br/><code>pow(2,pow(2,2))</code>的结果是16</td>
</tr>
<tr>
<td><code>print(x)</code></td>
<td>打印变量或字符串x<br/><code>print()</code>的end参数用来表示输出的结尾字符</td>
</tr>
<tr>
<td><code>range(a,b,s)</code></td>
<td>从a到b(不含)以s为步长产生一个序列<br /><code>list(range(1,10,3))</code>的结果是[1, 4, 7]</td>
</tr>
<tr>
<td><code>reversed(r)</code></td>
<td>返回组合类型r的逆序迭代形式<br/><code>for i in reversed([1,2,3])</code>将逆序遍历列表</td>
</tr>
<tr>
<td><code>round(n)</code></td>
<td>四舍五入方式计算n<br/><code>round(10.6)</code>的结果是11</td>
</tr>
<tr>
<td><code>set(x)</code></td>
<td>将组合数据类型x转换成集合类型<br/><code>set([1,1,1,1])</code>的结果是{1}</td>
</tr>
<tr>
<td><code>sorted(x)</code></td>
<td>对组合数据类型x进行排序，默认从小到大<br/><code>sorted([1,3,5,2,4])</code>的结果是<code>[1,2,3,4,5]</code></td>
</tr>
<tr>
<td><code>str(x)</code></td>
<td>将x转换为等值的字符串类型<br/><code>str(0x1010)</code>的结果是’4112’</td>
</tr>
<tr>
<td><code>sum(x)</code></td>
<td>对组合数据类型x计算求和结果<br/><code>sum([1,3,5,2,4])</code>的结果是15</td>
</tr>
<tr>
<td><code>type(x)</code></td>
<td>返回变量x的数据类型<br/><code>type({1:2})</code>的结果是<code>&lt;class &#39;dict&#39;&gt;</code></td>
</tr>
</tbody></table>

    </div>

    
    
    
      
  <div class="popular-posts-header">相关文章</div>
  <ul class="popular-posts">
    <li class="popular-posts-item">
      <div class="popular-posts-title"><a href="\2019\10\12\Python\Python有关配置\" rel="bookmark">Python有关配置</a></div>
    </li>
    <li class="popular-posts-item">
      <div class="popular-posts-title"><a href="\2019\08\07\Python\计算机二级公共基础\" rel="bookmark">计算机二级公共基础</a></div>
    </li>
  </ul>


      <footer class="post-footer">
          
          <div class="post-tags">
              <a href="/tags/Pyhton/" rel="tag"><i class="fa fa-tag"></i> Pyhton</a>
              <a href="/tags/%E8%AE%A1%E7%AE%97%E6%9C%BA%E4%BA%8C%E7%BA%A7/" rel="tag"><i class="fa fa-tag"></i> 计算机二级</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2019/08/13/Web/CSS%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/" rel="prev" title="CSS学习笔记">
      <i class="fa fa-chevron-left"></i> CSS学习笔记
    </a></div>
      <div class="post-nav-item">
    <a href="/2019/10/01/Python/%E5%87%BD%E6%95%B0%E5%BC%8F%E7%BC%96%E7%A8%8B/" rel="next" title="函数式编程">
      函数式编程 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#程序设计基本方法"><span class="nav-number">1.</span> <span class="nav-text">程序设计基本方法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#程序设计语言概述"><span class="nav-number">1.1.</span> <span class="nav-text">程序设计语言概述</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#计算机编程"><span class="nav-number">1.2.</span> <span class="nav-text">计算机编程</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#程序的基本编写方法"><span class="nav-number">1.3.</span> <span class="nav-text">程序的基本编写方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Python语言概述"><span class="nav-number">1.4.</span> <span class="nav-text">Python语言概述</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#实例"><span class="nav-number">1.5.</span> <span class="nav-text">实例</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Python基本语法元素"><span class="nav-number">2.</span> <span class="nav-text">Python基本语法元素</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#语法元素的名称"><span class="nav-number">2.1.</span> <span class="nav-text">语法元素的名称</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#数据类型"><span class="nav-number">2.2.</span> <span class="nav-text">数据类型</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#程序的语句元素"><span class="nav-number">2.3.</span> <span class="nav-text">程序的语句元素</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#基本输入输出函数"><span class="nav-number">2.4.</span> <span class="nav-text">基本输入输出函数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#实例解析–倒背如流"><span class="nav-number">2.5.</span> <span class="nav-text">实例解析–倒背如流</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#⭐基本数据类型"><span class="nav-number">3.</span> <span class="nav-text">⭐基本数据类型</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#⭐整数类型"><span class="nav-number">3.1.</span> <span class="nav-text">⭐整数类型</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#浮点数类型"><span class="nav-number">3.2.</span> <span class="nav-text">浮点数类型</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#复数类型"><span class="nav-number">3.3.</span> <span class="nav-text">复数类型</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#数字类型的运算"><span class="nav-number">3.4.</span> <span class="nav-text">数字类型的运算</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#运算操作符"><span class="nav-number">3.4.1.</span> <span class="nav-text">运算操作符</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#数值运算函数"><span class="nav-number">3.4.2.</span> <span class="nav-text">数值运算函数</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#字符串类型及格式化"><span class="nav-number">3.5.</span> <span class="nav-text">字符串类型及格式化</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#format-方法的基本使用"><span class="nav-number">3.5.1.</span> <span class="nav-text">format()方法的基本使用</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#字符串类型的操作"><span class="nav-number">3.6.</span> <span class="nav-text">字符串类型的操作</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#字符串操作符"><span class="nav-number">3.6.1.</span> <span class="nav-text">字符串操作符</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#字符串处理函数"><span class="nav-number">3.6.2.</span> <span class="nav-text">字符串处理函数</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#字符串处理方法"><span class="nav-number">3.6.3.</span> <span class="nav-text">字符串处理方法</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#类型判断和类型间转换"><span class="nav-number">3.6.4.</span> <span class="nav-text">类型判断和类型间转换</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#实例解析–凯撒密码"><span class="nav-number">3.7.</span> <span class="nav-text">实例解析–凯撒密码</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#程序的控制结构"><span class="nav-number">4.</span> <span class="nav-text">程序的控制结构</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#程序流程图"><span class="nav-number">4.1.</span> <span class="nav-text">程序流程图</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#程序控制结构"><span class="nav-number">4.2.</span> <span class="nav-text">程序控制结构</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#单分支结构-if语句"><span class="nav-number">4.3.</span> <span class="nav-text">单分支结构: if语句</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#二分支结构-if-else语句"><span class="nav-number">4.3.1.</span> <span class="nav-text">二分支结构: if-else语句</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#多分支结构-if-elif-else语句"><span class="nav-number">4.3.2.</span> <span class="nav-text">多分支结构: if-elif-else语句</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#判断条件及组合"><span class="nav-number">4.4.</span> <span class="nav-text">判断条件及组合</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#程序的循环结构"><span class="nav-number">4.5.</span> <span class="nav-text">程序的循环结构</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#遍历循环-for"><span class="nav-number">4.5.1.</span> <span class="nav-text">遍历循环: for</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#无限循环-while"><span class="nav-number">4.5.2.</span> <span class="nav-text">无限循环: while</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#循环控制-break和continue"><span class="nav-number">4.5.3.</span> <span class="nav-text">循环控制: break和continue</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#程序的异常处理"><span class="nav-number">4.6.</span> <span class="nav-text">程序的异常处理</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#try-except"><span class="nav-number">4.6.1.</span> <span class="nav-text">try  except</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#实例解析——猜数字游戏"><span class="nav-number">4.7.</span> <span class="nav-text">实例解析——猜数字游戏</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#函数和代码复用"><span class="nav-number">5.</span> <span class="nav-text">函数和代码复用</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#函数的定义：def"><span class="nav-number">5.1.</span> <span class="nav-text">函数的定义：def</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#函数的参数传递"><span class="nav-number">5.2.</span> <span class="nav-text">函数的参数传递</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#可选参数传递"><span class="nav-number">5.2.1.</span> <span class="nav-text">可选参数传递</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#参数名称传递"><span class="nav-number">5.2.2.</span> <span class="nav-text">参数名称传递</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#函数的返回值"><span class="nav-number">5.3.</span> <span class="nav-text">函数的返回值</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#变量的作用域"><span class="nav-number">5.4.</span> <span class="nav-text">变量的作用域</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#局部变量"><span class="nav-number">5.4.1.</span> <span class="nav-text">局部变量</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#全局变量"><span class="nav-number">5.4.2.</span> <span class="nav-text">全局变量</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#代码复用"><span class="nav-number">5.5.</span> <span class="nav-text">代码复用</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#实例解析–软文的诗词风"><span class="nav-number">5.6.</span> <span class="nav-text">实例解析–软文的诗词风</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#组合数据类型"><span class="nav-number">6.</span> <span class="nav-text">组合数据类型</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#组合数据类型基本概念"><span class="nav-number">6.1.</span> <span class="nav-text">组合数据类型基本概念</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#集合类型概述"><span class="nav-number">6.1.1.</span> <span class="nav-text">集合类型概述</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#序列类型概述"><span class="nav-number">6.1.2.</span> <span class="nav-text">序列类型概述</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#映射类型概述"><span class="nav-number">6.1.3.</span> <span class="nav-text">映射类型概述</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#列表类型"><span class="nav-number">6.2.</span> <span class="nav-text">列表类型</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#定义"><span class="nav-number">6.2.1.</span> <span class="nav-text">定义</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#索引"><span class="nav-number">6.2.2.</span> <span class="nav-text">索引</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#切片"><span class="nav-number">6.2.3.</span> <span class="nav-text">切片</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#列表类型的操作"><span class="nav-number">6.3.</span> <span class="nav-text">列表类型的操作</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#操作函数"><span class="nav-number">6.3.1.</span> <span class="nav-text">操作函数</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#列表的操作方法"><span class="nav-number">6.3.2.</span> <span class="nav-text">列表的操作方法</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#字典的索引"><span class="nav-number">6.4.</span> <span class="nav-text">字典的索引</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#字典的操作"><span class="nav-number">6.5.</span> <span class="nav-text">字典的操作</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#相关操作函数"><span class="nav-number">6.5.1.</span> <span class="nav-text">相关操作函数</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#操作方法"><span class="nav-number">6.5.2.</span> <span class="nav-text">操作方法</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#实例解析——文本词频统计"><span class="nav-number">6.6.</span> <span class="nav-text">实例解析——文本词频统计</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#文件和数据格式化"><span class="nav-number">7.</span> <span class="nav-text">文件和数据格式化</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#文件的使用"><span class="nav-number">7.1.</span> <span class="nav-text">文件的使用</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#文件的类型"><span class="nav-number">7.1.1.</span> <span class="nav-text">文件的类型</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#打开和关闭"><span class="nav-number">7.1.2.</span> <span class="nav-text">打开和关闭</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#文件的读写"><span class="nav-number">7.1.3.</span> <span class="nav-text">文件的读写</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#数据组织的维度"><span class="nav-number">7.2.</span> <span class="nav-text">数据组织的维度</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#一维数据"><span class="nav-number">7.2.1.</span> <span class="nav-text">一维数据</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#二维数据"><span class="nav-number">7.2.2.</span> <span class="nav-text">二维数据</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#高维数据"><span class="nav-number">7.2.3.</span> <span class="nav-text">高维数据</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#一维数据处理"><span class="nav-number">7.3.</span> <span class="nav-text">一维数据处理</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#表示"><span class="nav-number">7.3.1.</span> <span class="nav-text">表示</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#存储"><span class="nav-number">7.3.2.</span> <span class="nav-text">存储</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#处理"><span class="nav-number">7.3.3.</span> <span class="nav-text">处理</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#二维数据的处理"><span class="nav-number">7.4.</span> <span class="nav-text">二维数据的处理</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#表示方法"><span class="nav-number">7.4.1.</span> <span class="nav-text">表示方法</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#存储方式"><span class="nav-number">7.4.2.</span> <span class="nav-text">存储方式</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#处理代码"><span class="nav-number">7.4.3.</span> <span class="nav-text">处理代码</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#zip-函数"><span class="nav-number">7.4.4.</span> <span class="nav-text">zip()函数</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#实例解析–国家财政数据趋势演算"><span class="nav-number">7.5.</span> <span class="nav-text">实例解析–国家财政数据趋势演算</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Python-计算生态"><span class="nav-number">8.</span> <span class="nav-text">Python 计算生态</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#计算思维"><span class="nav-number">8.1.</span> <span class="nav-text">计算思维</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#程序设计方法论"><span class="nav-number">8.2.</span> <span class="nav-text">程序设计方法论</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#自顶向下设计：最重要是顶层设计"><span class="nav-number">8.2.1.</span> <span class="nav-text">自顶向下设计：最重要是顶层设计</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#自底向上执行"><span class="nav-number">8.2.2.</span> <span class="nav-text">自底向上执行</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#计算生态"><span class="nav-number">8.3.</span> <span class="nav-text">计算生态</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#实例解析–Web页面元素提取"><span class="nav-number">8.4.</span> <span class="nav-text">实例解析–Web页面元素提取</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Python-标准库概览"><span class="nav-number">9.</span> <span class="nav-text">Python 标准库概览</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#turtle库概述"><span class="nav-number">9.1.</span> <span class="nav-text">turtle库概述</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Python-第三方库概览"><span class="nav-number">10.</span> <span class="nav-text">Python 第三方库概览</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#获取和安装"><span class="nav-number">10.1.</span> <span class="nav-text">获取和安装</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#pip-工具"><span class="nav-number">10.1.1.</span> <span class="nav-text">pip 工具</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#自定义安装"><span class="nav-number">10.1.2.</span> <span class="nav-text">自定义安装</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#pip-工具使用"><span class="nav-number">10.1.3.</span> <span class="nav-text">pip 工具使用</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#PyInstaller-库"><span class="nav-number">10.2.</span> <span class="nav-text">PyInstaller 库</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#jieba-库"><span class="nav-number">10.3.</span> <span class="nav-text">jieba 库</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#wordcloud-库"><span class="nav-number">10.4.</span> <span class="nav-text">wordcloud 库</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#实例解析–《红楼梦》人物出场词云"><span class="nav-number">10.5.</span> <span class="nav-text">实例解析–《红楼梦》人物出场词云</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Python-第三方库纵览"><span class="nav-number">11.</span> <span class="nav-text">Python 第三方库纵览</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#网络爬虫方向"><span class="nav-number">11.1.</span> <span class="nav-text">网络爬虫方向</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#requests"><span class="nav-number">11.1.1.</span> <span class="nav-text">requests</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#scrapy"><span class="nav-number">11.1.2.</span> <span class="nav-text">scrapy</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#数据分析方向"><span class="nav-number">11.2.</span> <span class="nav-text">数据分析方向</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#numpy"><span class="nav-number">11.2.1.</span> <span class="nav-text">numpy</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#scipy"><span class="nav-number">11.2.2.</span> <span class="nav-text">scipy</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#pandas"><span class="nav-number">11.2.3.</span> <span class="nav-text">pandas</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#文本处理方向"><span class="nav-number">11.3.</span> <span class="nav-text">文本处理方向</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#pdfminer"><span class="nav-number">11.3.1.</span> <span class="nav-text">pdfminer</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#openpyxl"><span class="nav-number">11.3.2.</span> <span class="nav-text">openpyxl</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#python-docx"><span class="nav-number">11.3.3.</span> <span class="nav-text">python_docx</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#beautifulsoup4"><span class="nav-number">11.3.4.</span> <span class="nav-text">beautifulsoup4</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#数据可视化方向"><span class="nav-number">11.4.</span> <span class="nav-text">数据可视化方向</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#matplotlib"><span class="nav-number">11.4.1.</span> <span class="nav-text">matplotlib</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#TVTK"><span class="nav-number">11.4.2.</span> <span class="nav-text">TVTK</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#mayavi"><span class="nav-number">11.4.3.</span> <span class="nav-text">mayavi</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#用户图形界面方向"><span class="nav-number">11.5.</span> <span class="nav-text">用户图形界面方向</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#PyQt5"><span class="nav-number">11.5.1.</span> <span class="nav-text">PyQt5</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#wxPython"><span class="nav-number">11.5.2.</span> <span class="nav-text">wxPython</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#PyGTK"><span class="nav-number">11.5.3.</span> <span class="nav-text">PyGTK</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#机器学习方向"><span class="nav-number">11.6.</span> <span class="nav-text">机器学习方向</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#scikit-learn"><span class="nav-number">11.6.1.</span> <span class="nav-text">scikit-learn</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#TensorFlow"><span class="nav-number">11.6.2.</span> <span class="nav-text">TensorFlow</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Theano"><span class="nav-number">11.6.3.</span> <span class="nav-text">Theano</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Web-开发方向"><span class="nav-number">11.7.</span> <span class="nav-text">Web 开发方向</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Django"><span class="nav-number">11.7.1.</span> <span class="nav-text">Django</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Pyramid"><span class="nav-number">11.7.2.</span> <span class="nav-text">Pyramid</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Flask"><span class="nav-number">11.7.3.</span> <span class="nav-text">Flask</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#8-游戏开发方向"><span class="nav-number">11.8.</span> <span class="nav-text">8.游戏开发方向</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Pygame"><span class="nav-number">11.8.1.</span> <span class="nav-text">Pygame</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Panda3D"><span class="nav-number">11.8.2.</span> <span class="nav-text">Panda3D</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#cocos2d"><span class="nav-number">11.8.3.</span> <span class="nav-text">cocos2d</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#更多"><span class="nav-number">11.9.</span> <span class="nav-text">更多</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#PIL"><span class="nav-number">11.9.1.</span> <span class="nav-text">PIL</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#SymPY"><span class="nav-number">11.9.2.</span> <span class="nav-text">SymPY</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#NLTK"><span class="nav-number">11.9.3.</span> <span class="nav-text">NLTK</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#WeRoBot"><span class="nav-number">11.9.4.</span> <span class="nav-text">WeRoBot</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#MyQR"><span class="nav-number">11.9.5.</span> <span class="nav-text">MyQR</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#附录"><span class="nav-number">12.</span> <span class="nav-text">附录</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#常用-Unicode-编码表"><span class="nav-number">12.1.</span> <span class="nav-text">常用 Unicode 编码表</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#转义字符"><span class="nav-number">12.2.</span> <span class="nav-text">转义字符</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#基本的Python内置函数"><span class="nav-number">12.3.</span> <span class="nav-text">基本的Python内置函数</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Lanqilu"
      src="http://img.whl123456.top/image/avatar.jpg">
  <p class="site-author-name" itemprop="name">Lanqilu</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">85</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">18</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">39</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/lanqilu" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;lanqilu" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i></a>
      </span>
      <span class="links-of-author-item">
        <a href="http://mail.qq.com/cgi-bin/qm_share?t=qm_mailme&email=zqKvoL_noruOqKG2o6_nouCtoaM" title="E-Mail → http:&#x2F;&#x2F;mail.qq.com&#x2F;cgi-bin&#x2F;qm_share?t&#x3D;qm_mailme&amp;email&#x3D;zqKvoL_noruOqKG2o6_nouCtoaM" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i></a>
      </span>
  </div>



      </div>
        <div class="back-to-top motion-element">
          <i class="fa fa-arrow-up"></i>
          <span>0%</span>
        </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 2019 – 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Lanqilu</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/pjax/pjax.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js"></script>
  <script src="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/pangu@4/dist/browser/pangu.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>

  <script>
var pjax = new Pjax({
  selectors: [
    'head title',
    '#page-configurations',
    '.content-wrap',
    '.post-toc-wrap',
    '.languages',
    '#pjax'
  ],
  switches: {
    '.post-toc-wrap': Pjax.switches.innerHTML
  },
  analytics: false,
  cacheBust: false,
  scrollTo : !CONFIG.bookmark.enable
});

window.addEventListener('pjax:success', () => {
  document.querySelectorAll('script[data-pjax], script#page-configurations, #pjax script').forEach(element => {
    var code = element.text || element.textContent || element.innerHTML || '';
    var parent = element.parentNode;
    parent.removeChild(element);
    var script = document.createElement('script');
    if (element.id) {
      script.id = element.id;
    }
    if (element.className) {
      script.className = element.className;
    }
    if (element.type) {
      script.type = element.type;
    }
    if (element.src) {
      script.src = element.src;
      // Force synchronous loading of peripheral JS.
      script.async = false;
    }
    if (element.dataset.pjax !== undefined) {
      script.dataset.pjax = '';
    }
    if (code !== '') {
      script.appendChild(document.createTextNode(code));
    }
    parent.appendChild(script);
  });
  NexT.boot.refresh();
  // Define Motion Sequence & Bootstrap Motion.
  if (CONFIG.motion.enable) {
    NexT.motion.integrator
      .init()
      .add(NexT.motion.middleWares.subMenu)
      .add(NexT.motion.middleWares.postList)
      .bootstrap();
  }
  NexT.utils.updateSidebarPosition();
});
</script>




  




  
<script src="/js/local-search.js"></script>













    <div id="pjax">
  

  

  

    </div>
</body>
</html>
